[英]On click scroll to the top with 100px more
我使用一页网站,当我单击菜单按钮时,它会向下滚动到某些div的顶部...但是因为我使用的是固定标头,滚动到0px顶部,所以我需要像主体标签中的padding一样的100px top,但是我需要在函数中要说的是,我需要从页面顶部滚动到100px之后,滚动到项目顶部。 这是我的代码:
jQuery(document).ready(function($) {
$(".scroll").click(function(event){
event.preventDefault();
var x = $(this.hash).offset().top;
$('html,body').animate({scrollTop:x},2000);
});
});
如果我正确理解,只需在$(this.hash).offset().top
添加100px即可。
因为,偏移量是获取相对于文档的数据。
获取第一个元素的当前坐标,或设置匹配元素集中相对于文档的每个元素的坐标。 http://api.jquery.com/offset/
jQuery(document).ready(function($) { $(".scroll").click(function(event) { event.preventDefault(); var x = $(this).offset().top; $('html,body').animate({scrollTop: x - 100 }, 2000); }); });
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> </head> <body style="height: 1000px; padding-top: 100px"> <div class="scroll">click to scroll to me</div> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.