在jquery中向上和向下滚动元素

时间:2017-03-08 10:05:02

标签: javascript jquery html css

我想滚动到元素作为whatsapp搜索

用户点击search (here it is bottom)时应滚动到最后一个元素

即;标识为chat-7的元素。 点击up button时,应滚动至chat-6,然后chat-5 ..依此类推。

如果点击down button,如果它不是最后一项,则应向下滚动。



function scroll(id){
    console.log(id);
    $(".container").animate(
        { 
            scrollTop: $("#"+id).offset().top
        },
        "fast"
    );
}




这里有完整的代码 http://jsfiddle.net/p3kar5bb/231/

遗憾的是,此代码无法正常运行

4 个答案:

答案 0 :(得分:0)

在身体上执行动画而不是.container

function scroll(id){
console.log(id);
$("body").animate({ scrollTop: $("#"+id).offset().top}, "fast");

}

同时设置

var pointedPosition=0;

小提琴http://jsfiddle.net/p3kar5bb/234/

答案 1 :(得分:0)

因为你的div $("body").animate({ scrollTop: $("#"+id).parent('.item').offset().top}, "fast"); 没有滚动条,所以你可以做两件事。

<强> 1。动画身体

.container{
   height: 100%;
   overflow-y: scroll;
   max-height:200px;    
  }

Demo

<强> 2。将max-height设置为div

4.5.0

Demo

答案 2 :(得分:0)

$('html, body').animate({
scrollTop: $("#"+id).offset().top
}, 500);

http://jsfiddle.net/p3kar5bb/231/中给出的代码很好,只需更改上面的animate()。

刚试过 - $(&#39; html&#39;)在Chrome中不起作用且$(&#39; body&#39;)在Firefox中不起作用,所以$(&#39; html,body&需要#39;)。而且调用.stop()也是件好事。

答案 3 :(得分:0)

假设您有按钮点击事件的元素ID,请尝试将滚动功能代码更改为:

 function scroll(id){
      $('html, body').animate({ 
      scrollTop: $("#"+id).offset().top
        }, 2000);
}

我已在此处更新您的代码http://jsfiddle.net/p3kar5bb/231/