繁体   English   中英

如何使此滚动滚动到div脚本“平滑”

[英]How to make this scroll to div script “smooth”

因此,我是由该站点的用户找到此脚本的,但是我不记得作者了。 该脚本正在运行,但是我希望它能够“平滑地”滚动,而不仅仅是立即显示在我所需的信息上。 并尽可能使目标出现在div上方300像素处。

我怎么做?

 #general{ margin-top:900px; height: 100px; weight: 100px; background: green; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script> var hashTagActive = ""; $(".scroll").click(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().center > $(document).height() - $(window).height()) { dest = $(document).height() - $(window).height(); } else { dest = $(this.hash).offset().center; } //go to destination $('html,body').animate({ scrollTop: dest }, 2000, 'swing'); hashTagActive = this.hash; } }); </script> <div> <a class="scroll" href="#general">Hello</a> </div> <div id="general"> </div 

为了使滚动更流畅,可以使用:

$(document).ready(function() {
  $("ANCHOR LINK").click(function(event){     
    event.preventDefault();
    $("html, body").animate({scrollTop:$(this.hash).offset().top}, 1000);
  });
});

您看到最后一个号码了吗? 1000 ,使其变大使其变慢。

第二件事,恐怕我帮不了你。

为了顺利滚动到元素上方300px,您的JavaScript函数应如下所示:

$(".scroll").click(function (event) {
    $('html,body').animate({
        scrollTop: ($(this.hash).offset().top - 300)
    }, 2000);
    event.preventDefault();
});

如何制作#id链接的动画:

的jsfiddle

HTML

<a href="#content">Click me!</a><br>
<a href="google.com">Google.com</a>
<div id="content"></div>

CSS

#content {
    margin-top: 900px; 
    height: 100px; width: 100px;
    background-color: lightgreen;
}

jQuery的

$('a').on('click', function (event) {
    var target = $(this.hash),
        top;

    if (target) {
        top = target.offset().top;

        event.preventDefault();

        $('html, body').animate({
            scrollTop: top
        }, 600, 'swing');
    }
});

暂无
暂无

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

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