[英]How to make this scroll to div script “smooth”
So I found this script by a user of this site however I can't remember the author. 因此,我是由该站点的用户找到此脚本的,但是我不记得作者了。 The script is working, however I want it to scroll more "smoothly" than just instantly appear at my desired information. 该脚本正在运行,但是我希望它能够“平滑地”滚动,而不仅仅是立即显示在我所需的信息上。 And if possible, have the destination appear 300pixels above the div. 并尽可能使目标出现在div上方300像素处。
How do I do that? 我怎么做?
#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
For a smoother scroll you can use: 为了使滚动更流畅,可以使用:
$(document).ready(function() {
$("ANCHOR LINK").click(function(event){
event.preventDefault();
$("html, body").animate({scrollTop:$(this.hash).offset().top}, 1000);
});
});
And you see the last number? 您看到最后一个号码了吗? 1000
, make it bigger to make it slower. 1000
,使其变大使其变慢。
The second thing I'm afraid I can't help you with. 第二件事,恐怕我帮不了你。
For smooth scroll to 300px above top of the element, your JavaScript function should look like this : 为了顺利滚动到元素上方300px,您的JavaScript函数应如下所示:
$(".scroll").click(function (event) {
$('html,body').animate({
scrollTop: ($(this.hash).offset().top - 300)
}, 2000);
event.preventDefault();
});
How to animate to #id
links: 如何制作#id
链接的动画:
<a href="#content">Click me!</a><br>
<a href="google.com">Google.com</a>
<div id="content"></div>
#content {
margin-top: 900px;
height: 100px; width: 100px;
background-color: lightgreen;
}
$('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.