jquery滚动到指定位置

利用jquery实现页面可视区滚动到指定位置。直接上代码

//滚动到指定位置
  function scrollTo(element,speed) {
    if(!speed){
      speed = 300;
    }
    if(!element){
      $("html,body").animate({scrollTop:0},speed);
    }else{
      if(element.length>0){
        $("html,body").animate({scrollTop:$(element).offset().top-200},speed);
      }
    }
  }

//然后触发某个事件时调用这个函数。
//scrollTo('#comment',300);    写评论功能的时候,滚动到文本域的位置。#comment是文本域ID属性。

offset() 返回或设置匹配元素相对于文档的偏移。上述代码中  -200  的意思是是文本域再向下移动200px,实现此功能主要是scrollTop配合animate动画。

//回答顶部
$('html,body').animate({scrollTop: 0},500); //距离body顶部为0,scrollTop

参考:scrollTop讲解

$("html,body")是什么意思呢?暂时没明白。

原文地址:https://www.cnblogs.com/bneglect/p/10996247.html