页面加载时 jQuery 平滑滚动

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16534851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:19:02  来源:igfitidea点击:

jQuery Smooth Scrolling on Page Load

jquery

提问by Talon

I'm using this jQuery Script to do Smooth Scrolling (Found on CSS-Tricks.com):

我正在使用这个 jQuery 脚本来做平滑滚动(在 CSS-Tricks.com 上找到):

/** Smooth Scrolling Functionality **/
jQuery(document).ready(function($) {
  function filterPath(string) {
  return string
    .replace(/^\//,'')
    .replace(/(index|default).[a-zA-Z]{3,4}$/,'')
    .replace(/\/$/,'');
  }
  var locationPath = filterPath(location.pathname);
  var scrollElem = scrollableElement('html', 'body');
  var urlHash = '#' + window.location.href.split("#")[1];

  $('a[href*=#]').each(function() {
    $(this).click(function(event) {
    var thisPath = filterPath(this.pathname) || locationPath;
    if (  locationPath == thisPath
    && (location.hostname == this.hostname || !this.hostname)
    && this.hash.replace(/#/,'') ) {
      var $target = $(this.hash), target = this.hash;
      if (target) {
        var targetOffset = $target.offset().top;
          event.preventDefault();
          $(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
            location.hash = target;
          });
      }
    }
   });  
  });

  // use the first element that is "scrollable"
  function scrollableElement(els) {
    for (var i = 0, argLength = arguments.length; i <argLength; i++) {
      var el = arguments[i],
          $scrollElement = $(el);
      if ($scrollElement.scrollTop()> 0) {
        return el;
      } else {
        $scrollElement.scrollTop(1);
        var isScrollable = $scrollElement.scrollTop()> 0;
        $scrollElement.scrollTop(0);
        if (isScrollable) {
          return el;
        }
      }
    }
    return [];
  }

});
/** END SMOOTH SCROLLING FUNCTIONALITY **/

It works fantastic, except for one thing, I want it to work where if someone goes directly to the url e.g. http://domain.com/page.html#anchorit smooth scrolls to that anchor from the top on page load, right now it immediately goes to the page anchor unless they've clicked on an anchor. I hope that makes sense.

它工作得很好,除了一件事,我希望它在有人直接转到 url 的情况下工作,例如http://domain.com/page.html#anchor它在页面加载时从顶部平滑滚动到该锚点,现在它立即转到页面锚点,除非他们点击在锚上。我希望这是有道理的。

回答by Naveed

If it is not too late for answer then here you go.... Here is a modification of PSR's code that actually works for smooth scrolling of page on load:

如果现在回答还为时不晚,那么您就可以开始了……这是对 PSR 代码的修改,实际上可以在加载时平滑滚动页面:

http://jsfiddle.net/9SDLw/1425/

http://jsfiddle.net/9SDLw/1425/

$(function(){
    $('html, body').animate({
        scrollTop: $( $('#anchor1').attr('href') ).offset().top
    }, 2000);
    return false;
});

Better version:

更好的版本:

http://jsfiddle.net/9SDLw/1432/

http://jsfiddle.net/9SDLw/1432/

$(function(){
    $('html, body').animate({
        scrollTop: $('.myclass').offset().top
    }, 2000);
    return false;
});

All you need to do in this script is to replace the "myclass" with a class or ID of the control located on the page you want to scroll to.

在这个脚本中你需要做的就是用你想要滚动到的页面上的控件的类或 ID 替换“myclass”。

Naveed

纳维德

回答by Talon

I found this to be the best way to do what I want so far:

我发现这是迄今为止做我想做的最好的方法:

/** Smooth Scrolling Functionality **/
var jump=function(e)
{
    //alert('here');
   if (e){
       //e.preventDefault();
       var target = jQuery(this).attr("href").replace('/', '');
   }else{
       var target = location.hash;
   }

   jQuery('html,body').animate(
   {
       scrollTop: (jQuery(target).offset().top) - 100
   },500,function()
   {
       //location.hash = target;
   });

}

jQuery('html, body').hide();

jQuery(document).ready(function($)
{
    $(document).on('click', 'a[href*=#]', jump);

    if (location.hash){
        setTimeout(function(){
            $('html, body').scrollTop(0).show();
            jump();
        }, 0);
    }else{
        $('html, body').show();
    }
});
/** END SMOOTH SCROLLING FUNCTIONALITY **/

回答by Bloghopper

@ Talons post ...

@Talons 帖子...

I found this to be the best way to do what I want so far:

我发现这是迄今为止做我想做的最好的方法:

Me 2, but I had to make some changes to it.

我 2,但我不得不对它做一些改变。

var target = jQuery(this).attr("href").replace('/', '');

1. Why replace the "/"?

1. 为什么要替换“/”?

In my case it makes the url...

就我而言,它使网址...

"http:// [my domain]/ [my page]/ [my anchor]" ...look like...

“http://[我的域]/[我的页面]/[我的锚点]”……看起来像……

"http:/ [my domain]/ [my page]/ [my anchor]"

“http:/ [我的域名]/ [我的页面]/ [我的锚点]”

and...

和...

2. Chrome (my current version: 40.0.2214.115 m) doesn't like the following Line...

2. Chrome(我当前的版本:40.0.2214.115 m)不喜欢以下行...

   jQuery('html,body').animate(
   {
       scrollTop: (jQuery(target).offset().top) - 100
   },500,function()
   {
       //location.hash = target;
   });

Uncaught Error: Syntax error, unrecognized expression: http:/ [my domain]/ [my page]/ [my anchor]

未捕获的错误:语法错误,无法识别的表达式:http://[我的域]/[我的页面]/[我的锚点]

I found out that jQuery cannot work with "offset" when "target" is a full href like http:// .../#anchor.

我发现当“目标”是像 http://.../#anchor 这样的完整 href 时,jQuery 无法使用“偏移量”。

to fix 1.

修复 1。

replaced:

替换:

var target = jQuery(this).attr("href").replace('/', '');

with:

和:

var target = jQuery(this).attr("href");

to fix 2.

修复 2。

replaced:

替换:

   jQuery('html,body').animate(
   {
       scrollTop: (jQuery(target).offset().top) - 100
   },500,function()
   {
       //location.hash = target;
   });

with:

和:

if(target.search('/') === -1) { //only do scroll if page with anchor is the currently loaded page
   jQuery('html,body').animate(
   {
       scrollTop: (jQuery(target).offset().top) - 100
   },500"easeInOutExpo"); // requires easing
}

Now works perfectly for me, without any errors. Please comment on this one, for I am pretty new in js/jquery...

现在非常适合我,没有任何错误。请对此发表评论,因为我在 js/jquery 中很新...

thx @Talon

谢谢@Talon

回答by PSR

You can do by using .scrollTop()

您可以使用.scrollTop()

$('a').click(function(){
    $('html, body').animate({
        scrollTop: $( $.attr(this, 'href') ).offset().top
    }, 2000);
    return false;
});

SEE HERE

看这里