在列表中移动时可视地跟踪项目

时间:2015-04-17 18:33:34

标签: jquery

我目前有一个项目清单,我允许用户重新安排;请查看代码段。

重新安排运作良好,但我在列表框上有一个固定的高度,我希望突出显示的项目在列表中上下移动时保持可见。

要重新创建我的问题,只需按几次 Move Down 按钮,第2项就会消失。您必须滚动才能再次看到它。这种行为是不可取的。

非常感谢任何指导!



$('.move-up').on('click', function(){
    var $active = $('.active');
    $active.insertBefore($active.prev('div'));
    scroll_to_element();
});
$('.move-down').on('click', function(){
    var $active = $('.active');
    $active.insertAfter($active.next('div'));
    scroll_to_element();
});

function scroll_to_element(){
    $('.list').animate({
        scrollTop: $(".active").offset().top
    }, 0);
}

.list{
    overflow:scroll;
    height:200px;
}
.list div{
    padding:10px;
}
.list div.active {
    background-color: #ffff7f;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="list">
    <div>Item 1</div>
    <div class="active">Item 2</div>
    <div>Item 3</div>
    <div>Item 4</div>
    <div>Item 5</div>
    <div>Item 6</div>
    <div>Item 7</div>
    <div>Item 8</div>
    <div>Item 9</div>
    <div>Item 10</div>
</div>

<button type="button" class="move-up">Move Up</button>
<button type="button" class="move-down">Move Down</button>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

如果你愿意触发滚动到desirect元素,你可以使用VelocityJS轻松实现 它是一个很好的图书馆(50kb),非常适合动画和滚动事件。

只需添加类似滚动演示的内容,以满足您的需求Velicoy SCROLL Demo

$("#element3").velocity("scroll", { 
  container: $("#container"),
  duration: 800,
  delay: 500
});