繁体   English   中英

jquery顺利滚动到锚点?

[英]jquery smooth scroll to an anchor?

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

喜欢:

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

我是这样做的:

    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;
        }
    });

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

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

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

我会使用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;
      }
    }
  });
});

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

到目前为止我见过的最佳解决方案: jQuery:Smooth Scrolling Internal Anchor Links

HTML:

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

脚本:

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

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

你可以传递各种不同的东西:

  • 原始数字
  • 字符串('44','100px','+ = 30px'等)
  • DOM元素(逻辑上,可滚动元素的子元素)
  • 一个选择器,它将相对于可滚动元素
  • 字符串'max'滚动到结尾。
  • 一个字符串,指定滚动到容器的该部分的百分比(fe:50%转到*到中间)。
  • 哈希{top:x,left:y},x和y可以是任何类型的数字/字符串,如上所述。

这是我用来快速将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;
});

我想要一个适用于<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>

试试这个吧。 这是我修改的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;
      }
    }
  });
});

使用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;
};

用法:

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

持续时间和宽松的默认值是400毫秒和“摆动”。

我在我的网站上使用了这个:

$(document).ready(function(){
$('a[href^="#"]').on('click',function (e) {
    e.preventDefault();

    var target = this.hash,
    $target = $(target);

    $('html, body').stop().animate({
        'scrollTop': $target.offset().top
    }, 1200, 'swing', function () {
        window.location.hash = target;
    });
});

});

您可以更改滚动的速度,更改我默认使用的“1200”,它在大多数浏览器上运行得相当好。

将代码放在页面的<head> </head>标记之后,您需要在<body>标记中创建内部链接:

<a href="#home">Go to Home</a>

希望能帮助到你!

Ps:别忘了打电话:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>

我在http://plugins.jquery.com/smooth-scroll/上使用了插件Smooth Scroll 使用此插件,您需要包含的是jQuery和插件代码的链接:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="javascript/smoothscroll.js"></script>

(链接需要使用smoothScroll类才能工作)。

Smooth Scroll的另一个功能是ancor名称不会显示在URL中!

作品

$('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);
            }
        }
    });
});

我讨厌在我的代码中添加函数命名的类,所以我把它放在一起。 如果我要停止使用平滑滚动,我会觉得有必要通过我的代码,并删除所有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>

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

它能做什么:
1.该函数使用href值来创建anchorID对象
- 在示例中,它是$('#contact')/about/开头
2. HTMLBODY被动画anchorID的顶部偏移量
- speed ='normal'('fast','slow',毫秒,)
- 宽松='摇摆'('线性'等...谷歌宽松)
3. return false - 它阻止浏览器在URL中显示哈希值
- 脚本在没有它的情况下工作,但它并不像“ 平滑 ”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM