在项目在列表中移动时直观地跟随项目



我目前有一个项目列表,我允许用户重新排列;请查看代码片段。

重新排列效果很好,但我在列表框上有一个固定的高度,我希望突出显示的项目在列表中上下移动时保持在视线范围内。

要重新创建我的问题,只需点击几次"下移"按钮,第 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>

如果您愿意触发滚动到 desirect 元素,您可以使用 VelocityJS 轻松做到这一点这是一个不错的图书馆(50kb),非常适合动画和滚动活动。

只需添加类似滚动演示的内容即可满足您的需求 Velicoy SCROLL 演示

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

最新更新