Javascript 如何使此卷轴在内容上方120px?
当我应用这个脚本时,它会转到链接,但我希望它比链接的内容高出120像素 代码如下:Javascript 如何使此卷轴在内容上方120px?,javascript,jquery,scroll,smooth-scrolling,Javascript,Jquery,Scroll,Smooth Scrolling,当我应用这个脚本时,它会转到链接,但我希望它比链接的内容高出120像素 代码如下: <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
<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 !== 0) {
// 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
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
</script>
$(文档).ready(函数(){
//添加平滑滚动到所有链接
$(“a”)。在('click',函数(事件){
//在覆盖默认行为之前,请确保this.hash具有值
if(this.hash!==0){
//防止默认锚点单击行为
event.preventDefault();
//存储散列
var hash=this.hash;
//使用jQuery的animate()方法添加平滑页面滚动
//可选数字(800)指定滚动到指定区域所需的毫秒数
$('html,body')。设置动画({
scrollTop:$(散列).offset().top
},800,函数(){
//完成滚动后,将哈希(#)添加到URL(默认单击行为)
window.location.hash=散列;
});
}//如果结束,则结束
});
});
编辑#02
以下是我的HTML、CSS和Java,供那些想知道:
只需从计算中减去像素量即可
$(文档).ready(函数(){
//添加平滑滚动到所有链接
$(“a”)。在('click',函数(事件){
//在覆盖默认行为之前,请确保this.hash具有值
if(this.hash!==0){
//防止默认锚点单击行为
event.preventDefault();
//存储散列
var hash=this.hash;
//使用jQuery的animate()方法添加平滑页面滚动
//可选数字(800)指定滚动到指定区域所需的毫秒数
$('html,body')。设置动画({
scrollTop:$(散列).offset().top-120
},800,函数(){
//完成滚动后,将哈希(#)添加到URL(默认单击行为)
window.location.hash=散列;
});
}//如果结束,则结束
});
});代码>问题是window.location.hash=hash代码>在设置动画后
执行与默认操作相同的第二个操作。替换为history.pushState(null,null,hash)
重写url历史记录并添加哈希
$('html, body').animate({
scrollTop: $(hash).offset().top - 120
}, 800, function() {
// Add hash (#) to URL when done scrolling (default click behavior)
//window.location.hash = hash;
history.pushState(null, null, hash);
});
欢迎来到SO。请将相关的HTML添加到我为您制作的代码片段中。请选择jQuery作为框架。单击并向下滚动,然后单击上面的“编辑”代码段,那么为什么不scrollTop:($(hash).offset().top-120)+“px”
?@mplungjan axpers,当我更改和替换代码时它不起作用,因为它在使用原始代码时会在相同的位置回退。这也不起作用。当我点击其中一个时,它会跳回,你需要点击两次,然后它才会做它的事情。(你的代码确实有效,但你需要点击两次)你真了不起。