Javascript 如何将平滑滚动JQuery动画的偏移量更改为导航栏的高度
我所有的平滑滚动都能完美地工作,但是,锚停在页面的顶部,但是我的导航栏固定在顶部,所以我需要它做的是,将顶部偏移导航栏的高度。我该怎么办Javascript 如何将平滑滚动JQuery动画的偏移量更改为导航栏的高度,javascript,jquery,smooth-scrolling,Javascript,Jquery,Smooth Scrolling,我所有的平滑滚动都能完美地工作,但是,锚停在页面的顶部,但是我的导航栏固定在顶部,所以我需要它做的是,将顶部偏移导航栏的高度。我该怎么办 <script> $(document).ready(function(){ // Add smooth scrolling to all links $("a").on('click', function(event) { // Make sure this.hash has a value before ove
<script>
$(document).ready(function(){
// Add smooth scrolling to all links
$("a").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds
// it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 1000, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
</script>
$(文档).ready(函数(){
//添加平滑滚动到所有链接
$(“a”)。在('click',函数(事件){
//在覆盖默认行为之前,请确保this.hash具有值
如果(this.hash!==“”){
//防止默认锚点单击行为
event.preventDefault();
//存储散列
var hash=this.hash;
//使用jQuery的animate()方法添加平滑页面滚动
//可选数字(800)指定毫秒数
//滚动到指定区域需要多长时间
$('html,body')。设置动画({
scrollTop:$(散列).offset().top
},1000,函数(){
//完成滚动后,将哈希(#)添加到URL(默认单击行为)
window.location.hash=散列;
});
}//如果结束,则结束
});
});
相当简单:scrollTop:$('#hash').offset().top-navbarHeight
相当简单:scrollTop:$('#hash').offset().top-navbarHeight
我是否需要将navbarHeight放在任何括号中,或者使用任何特定的单位?@FilipGrebowski,如果您知道类似于scrollTop:$(hash).offset().top-48
。或者使用如下内容以编程方式获取导航栏的高度:scrollTop:$(散列).offset().top-$(#navbarId).height()
.Hmm。。它似乎不起作用。我的意思是,我完全同意这个逻辑,但要么它没有效果,要么完全没有模式。你还有其他想法吗?ID不应该在括号中吗?我需要navbarHeight在任何括号中,或者使用任何特定的单位吗?@FilipGrebowski,如果你知道它,你可以使用一个数字,比如scrollTop:$(hash).offset().top-48
。或者使用如下内容以编程方式获取导航栏的高度:scrollTop:$(散列).offset().top-$(#navbarId).height()
.Hmm。。它似乎不起作用。我的意思是我完全同意这个逻辑,但是要么它没有效果,要么它完全溢出,没有模式。你还有其他想法吗?ID不应该在括号中吗?