偏移 <a> href = id



当我点击<a class="Navigation" id="WorldHeader" href="#WorldTitle">Go to World</a>时,我的窗口直接将带有id的div直接放在顶部。有没有办法在我点击标签时偏移窗口位置?我的标题隐藏了内容,但我想保留它。

解决方案

假设基于 JQuery 标记并使用 @WebMarie 的引用,以下解决方案必须对您有所帮助:

$('#WorldHeader').on('click', function(event) {
event.preventDefault(); // Prevent the default <a> action.
let myOffset = 50; // Pixels.
let newScrollPosition = $("#WorldTitle").offset().top - myOffset;
$('html, body').scrollTop(newScrollPosition); // Set the current vertical position of the scroll bar.
});

带动画:

$('#WorldHeader').on('click', function(event) {
event.preventDefault();
let myOffset = 50; // Pixels.
let animationDuration = 1000; // Miliseconds.
let newScrollPosition = $("#WorldTitle").offset().top - myOffset;
$('html, body').animate({
scrollTop: newScrollPosition // Set the current vertical position of the scroll bar.
}, animationDuration);
});

使用示例

$('#WorldHeader').on('click', function(event) {
event.preventDefault();
let myOffset = 50; // Pixels.
let animationDuration = 1000; // Miliseconds.
let newScrollPosition = $("#WorldTitle").offset().top - myOffset;
$('html, body').animate({
scrollTop: newScrollPosition // Set the current vertical position of the scroll bar.
}, animationDuration);
});
#WorldTitle {
margin: 20px 0;
width: 100%;
height: 150px;
background-color: red;
}
.blue {
width: 100%;
height: 500px;
background-color: blue;
}
.green {
width: 100%;
height: 500px;
background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="Navigation" id="WorldHeader" href="#WorldTitle">Go to World</a>
<div class="blue"></div>
<div id="WorldTitle"></div>
<div class="green"></div>

相关内容

  • 没有找到相关文章

最新更新