Сортируемый jQuery - прокрутка в div с переполнением: автоматическая

StackOverflow https://stackoverflow.com/questions/961456

  •  12-09-2019
  •  | 
  •  

Вопрос

У меня есть страница, использующая jQuery, с некоторыми списками, которые были сделаны сортируемыми.Список находится внутри div, который имеет фиксированную высоту и значение переполнения auto в таблице стилей.

Атрибут прокрутки sortable, похоже, влияет на прокрутку всей страницы, есть ли какой-нибудь способ заставить контейнер div автоматически прокручиваться вверх или вниз, когда мышь находится у края?

Спасибо

Грэм

Это было полезно?

Решение

Я бы взглянул на этот плагин jQuery, который я использовал, и нашел довольно приятным:

http://rascarlito.free.fr/hoverscroll/

Пока, Сирил

Другие советы

Спасибо и Максу, и Файасару.Я заставил его работать с Jquery 1.4.2.Единственное, что я должен изменить, это

$().mousemove(function(e) {...});
//change it to 
this.mousemove(function(e) {...});

Теперь сортируется в фиксированном div с фиксированной высотой и переполнением: auto теперь работает нормально.Спасибо!

Посмотрите, сможете ли вы воспользоваться jQuery Прокрутите до плагин.Я предполагаю, что вы говорите об автоматической прокрутке в зависимости от близости мыши к краям контейнера div.

Грэм, Я попробовал ваше scripterlative.com мнение, но через несколько дней после истечения срока действия скрипта этого парня и отображения информационного сообщения о пробной версии на экране :)

После этого я разработал небольшой плагин jquery для легкого решения этой проблемы.

Когда вы используете этот плагин, он автоматически определяет границы элементов селектора, С другой стороны, вы также можете поместить сортировку jquery внутрь этого divs.

Не забывайте, что этот плагин зависит от плагина Jquery.Scrollto.

Это решило мою проблему, я надеюсь, что это поможет вам.

Источником плагина является ;

/*
* jQuery Html element edges auto scrollable plugin.
*
* Copyright (c) 2009 Fatih YASAR
*/
(function($) {
    $.fn.setEdgesAutoScrollable = function(options) {
        var defaults = {
            scrollspeed: 200,
            incrementSeed: 20
        };

        var options = $.extend(defaults, options)

        var top = $(this).offset().top;
        var left = $(this).offset().left;
        var height = $(this).height();
        var width = $(this).width();
        var selectedItemSelector = this.selector;

        var xmin = left;
        var xmax = (width + left) + 20;

        var ymin = (height + top) + 10;
        var ymax = (height + top) + 30;


        $().mousemove(function(e) {
        if (e.pageX > xmin && e.pageX < xmax) {
                if (e.pageY > (top - 10) && e.pageY < (top + 10)) {
                    //top edges
                    $(selectedItemSelector).scrollTo('-=' + defaults.incrementSeed + 'px', defaults.scrollspeed);
                } else if (e.pageY > ymin && e.pageY < ymax) {
                    //bottom edges
                    $(selectedItemSelector).scrollTo('+=' + defaults.incrementSeed + 'px', defaults.scrollspeed);
                } else {
                    $(selectedItemSelector).stop();
                }
            }

            return true;
        });
    }
})(jQuery);

Пример html-страницы для демонстрации того, как использовать.Источником Html-страницы является ;

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>

    <script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
    <script src="js/jquery.scrollTo-min.js" type="text/javascript"></script>
    <script src="js/[plugin src]" type="text/javascript"></script>
    <style>
    body
    {
        font-family: "Trebuchet MS" , "Helvetica" , "Arial" , "Verdana" , "sans-serif";
        font-size:13px;
    }

     .scrollable-wrapper
     {
        width:650px;
        height:350px;
     }   
     .scrollable-area
     {
        float:left;
        width:220px;
        height:350px;
        border:solid 2px #ccc;   
        margin-left:20px;      
        overflow:auto;
     }
    </style>
    <script>
        $(function() {
            $("#scrollable-area1").setEdgesAutoScrollable();
            $("#scrollable-area2").setEdgesAutoScrollable();
        });
    </script>
</head>
<body>
    <div class="scrollable-wrapper">
      <div id="scrollable-area1" class="scrollable-area">
       <p> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software </p>
       <p> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software </p>
       <p> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software </p>     
      </div>
      <div id="scrollable-area2" class="scrollable-area">
       <p> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software </p>
       <p> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software </p>
       <p> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software </p>      
      </div>
    </div>

</body>
</html>

Мне удалось внедрить решение fyasar, и оно отлично работает для меня.Я немного расширил его плагин и хотел опубликовать его здесь для всех, кто еще наткнется на его замечательный фрагмент кода.

Проблема, с которой я столкнулся с его решением, заключалась в том, что оно не давало гибкости для контроля того, где будет располагаться "поле" в верхней и нижней части окна, которое запускало бы прокрутку.Этот бит был жестко запрограммирован в его решении.

Я немного расширил логику и изменил плагин, чтобы он принимал смещения сверху и снизу, чтобы контролировать размер этого поля в верхней и нижней части поля.

Эти параметры теперь по умолчанию соответствуют тем, которые, по моему мнению, являются наиболее разумными точками для прокрутки.Но каждое использование элемента управления может передаваться в желаемом диапазоне в качестве параметров.

    (function($) {
    $.fn.setEdgesAutoScrollable = function(options) {
        var defaults = {
            scrollspeed: 200,
            incrementSeed: 20,
            topOffsetTop: -10,
            topOffsetBottom: 30,
            bottomOffsetTop: -20,
            bottomOffsetBottom: 20
        };

        var options = $.extend(defaults, options)

        var top = $(this).offset().top;
        var left = $(this).offset().left;
        var height = $(this).height();
        var width = $(this).width();
        var selectedItemSelector = this.selector;

        var bottom = (top + height);
        var right = (left + width);

        var xmin = left;
        var xmax = right + 20; // take scrollbar into account

        var topScrollTop = top + defaults.topOffsetTop;
        var topScrollBottom = top + defaults.topOffsetBottom;

        var bottomScrollTop = bottom + defaults.bottomOffsetTop;
        var bottomScrollBottom = bottom + defaults.bottomOffsetBottom;

        $().mousemove(function(e) {

            var myPageX = e.pageX;
            var myPageY = e.pageY;

            if (myPageX > xmin && myPageX < xmax) {

                if (myPageY > topScrollTop && myPageY < topScrollBottom) {
                    //top edges
                    $(selectedItemSelector).scrollTo('-=' + defaults.incrementSeed + 'px', defaults.scrollspeed);
                } else if (myPageY > bottomScrollTop && myPageY < bottomScrollBottom) {
                    //bottom edges
                    $(selectedItemSelector).scrollTo('+=' + defaults.incrementSeed + 'px', defaults.scrollspeed);
                } else {
                    $(selectedItemSelector).stop();
                }
            }

            return true;
        });
    }
})(jQuery);

Я надеюсь, что это поможет всем, кто еще столкнется с этой проблемой с помощью отличного элемента управления jquery.ui sortable.

  • Макс.
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top