Javascript jquery平滑滚动到锚点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4198041/
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-23 11:20:43  来源:igfitidea点击:

jquery smooth scroll to an anchor?

javascriptjquery

提问by dynamic

Is there a way to scroll down to an anchor link using jQuery?

有没有办法使用 jQuery 向下滚动到锚链接?

Like:

喜欢:

$(document).ready(function(){
  $("#gotomyanchor").click(function(){
      $.scrollSmoothTo($("#myanchor"));
  });
});

?

?

回答by hanoo

Here is how I do it:

这是我如何做到的:

    var hashTagActive = "";
    $(".scroll").on("click touchstart" , function (event) {
        if(hashTagActive != this.hash) { //this will prevent if the user click several times the same link to freeze the scroll.
            event.preventDefault();
            //calculate destination place
            var dest = 0;
            if ($(this.hash).offset().top > $(document).height() - $(window).height()) {
                dest = $(document).height() - $(window).height();
            } else {
                dest = $(this.hash).offset().top;
            }
            //go to destination
            $('html,body').animate({
                scrollTop: dest
            }, 2000, 'swing');
            hashTagActive = this.hash;
        }
    });

Then you just need to create your anchor like this:

然后你只需要像这样创建你的锚点:

<a class="scroll" href="#destination1">Destination 1</a>

You can see it on my website.
A demo is also available here: http://jsfiddle.net/YtJcL/

你可以在我的网站上看到它。
这里也有一个演示:http: //jsfiddle.net/YtJcL/

回答by David

I would use the simple code snippet from CSS-Tricks.com:

我将使用来自 CSS-Tricks.com 的简单代码片段:

$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});

Source: http://css-tricks.com/snippets/jquery/smooth-scrolling/

来源http: //css-tricks.com/snippets/jquery/smooth-scrolling/

回答by aruizca

Best solution I have seen so far: jQuery: Smooth Scrolling Internal Anchor Links

迄今为止我见过的最佳解决方案: jQuery: Smooth Scrolling Internal Anchor Links

HTML:

HTML:

<a href="#comments" class="scroll">Scroll to comments</a>

Script:

脚本:

jQuery(document).ready(function($) {
    $(".scroll").click(function(event){     
        event.preventDefault();
        $('html,body').animate({scrollTop:$(this.hash).offset().top}, 500);
    });
});

回答by Mark Biek

jQuery.scrollTowill do everything you want and more!

jQuery.scrollTo会做你想做的一切,甚至更多!

You can pass it all kinds of different things:

您可以将各种不同的东西传递给它:

  • A raw number
  • A string('44', '100px', '+=30px', etc )
  • A DOM element (logically, child of the scrollable element)
  • A selector, that will be relative to the scrollable element
  • The string 'max' to scroll to the end.
  • A string specifying a percentage to scroll to that part of the container (f.e: 50% goes to * to the middle).
  • A hash { top:x, left:y }, x and y can be any kind of number/string like above.
  • 一个原始数字
  • 一个字符串('44'、'100px'、'+=30px'等)
  • 一个 DOM 元素(逻辑上,可滚动元素的子元素)
  • 一个选择器,它将相对于可滚动元素
  • 要滚动到末尾的字符串 'max'。
  • 一个字符串,指定滚动到容器该部分的百分比(fe: 50% 转到 * 到中间)。
  • 散列 { top:x, left:y }, x 和 y 可以是任何类型的数字/字符串,如上所示。

回答by teh_senaus

Here's the code I used to quickly bind jQuery scrollTo to all anchor links:

这是我用来快速将 jQuery scrollTo 绑定到所有锚链接的代码:

// Smooth scroll
$('a[href*=#]').click(function () {
    var hash = $(this).attr('href');
    hash = hash.slice(hash.indexOf('#') + 1);
    $.scrollTo(hash == 'top' ? 0 : 'a[name='+hash+']', 500);
    window.location.hash = '#' + hash;
    return false;
});

回答by Justin

I wanted a version that worked for <a href="#my-id">and <a href="/page#my-id">

我想要一个适用于<a href="#my-id">和的版本<a href="/page#my-id">

<script>        
    $('a[href*=#]:not([href=#])').on('click', function (event) {
        event.preventDefault();
        var element = $(this.hash);
        $('html,body').animate({ scrollTop: element.offset().top },'normal', 'swing');
    });
</script>

回答by Piacenti

Try this one. It is a code from CSS tricks that I modified, it is pretty straight forward and does both horizontal and vertial scrolling. Needs JQuery. Here is a demo

试试这个。这是我修改过的 CSS 技巧中的代码,它非常简单,可以进行水平和垂直滚动。需要 JQuery。这是一个演示

$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top-10, scrollLeft:target.offset().left-10
        }, 1000);
        return false;
      }
    }
  });
});

回答by mpen

Using hanoo's scriptI created a jQuery function:

使用hanoo 的脚本我创建了一个 jQuery 函数:

$.fn.scrollIntoView = function(duration, easing) {
    var dest = 0;
    if (this.offset().top > $(document).height() - $(window).height()) {
        dest = $(document).height() - $(window).height();
    } else {
        dest = this.offset().top;
    }
    $('html,body').animate({
        scrollTop: dest
    }, duration, easing);
    return this;
};

usage:

用法:

$('#myelement').scrollIntoView();

Defaults for duration and easing are 400ms and "swing".

持续时间和缓动的默认值为 400 毫秒和“摆动”。

回答by user3715723

works

作品

$('a[href*=#]').each(function () {
    $(this).attr('href', $(this).attr('href').replace('#', '#_'));
    $(this).on( "click", function() {

        var hashname = $(this).attr('href').replace('#_', '');

        if($(this).attr('href') == "#_") {
            $('html, body').animate({ scrollTop: 0 }, 300);
        }
        else {
            var target = $('a[name="' + hashname + '"], #' + hashname),
                targetOffset = target.offset().top;
            if(targetOffset >= 1) {
                $('html, body').animate({ scrollTop: targetOffset-60 }, 300);
            }
        }
    });
});

回答by Dawson

I hate adding function-named classes to my code, so I put this together instead. If I were to stop using smooth scrolling, I'd feel behooved to go through my code, and delete all the class="scroll" stuff. Using this technique, I can comment out 5 lines of JS, and the entire site updates. :)

我讨厌在我的代码中添加函数命名的类,所以我把它们放在一起。如果我停止使用平滑滚动,我觉得应该检查我的代码,并删除所有 class="scroll" 内容。使用这种技术,我可以注释掉 5 行 JS,并且整个站点更新。:)

<a href="/about">Smooth</a><!-- will never trigger the function -->
<a href="#contact">Smooth</a><!-- but he will -->
...
...
<div id="contact">...</div>


<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
    // Smooth scrolling to element IDs
    $('a[href^=#]:not([href=#])').on('click', function () {
        var element = $($(this).attr('href'));
        $('html,body').animate({ scrollTop: element.offset().top },'normal', 'swing');
        return false;
    });
</script>

Requirements:
1. <a>elements must have an href attribute that begin with #and be more than just #
2. An element on the page with a matching idattribute

What it does:
1. The function uses the href value to create the anchorIDobject
   - In the example, it's $('#contact'), /aboutstarts with /
2. HTML, and BODYare animated to the top offset of anchorID
   - speed = 'normal' ('fast','slow', milliseconds, )
   - easing = 'swing' ('linear',etc ... google easing)
3. return false-- it prevents the browser from showing the hash in the URL
   - the script works without it, but it's not as "smooth".

要求
1,<a>元素必须有一个开头href属性#,并不仅仅是#
2.元素在页面上有一个匹配的id属性

作用:
1.函数使用href值来创建anchorID对象
   -在这个例子中,它是$('#contact')/about/
2.开始HTML,并且BODY动画到顶部偏移anchorID
   - speed = 'normal' ('fast','slow', milliseconds, )
   - easing = 'swing' ('linear',etc ... google easing )
3. return false-- 它阻止浏览器在 URL 中显示哈希
   - 脚本在没有它的情况下工作,但它不像“光滑”。