我添加了粘性标题和平滑滚动效果,但我不知道如何修复位置,以便它与标题大小一起计算。我尝试过的事情完全禁用了粘性标题。
我尝试过使用几种不同的技术,尽管我是新手,而且对我自己来说可能太难了。
<div id="container">
<section id="sectionHome">
<!--Header and Logo-->
<header id="myHeader">
<logo>
<img src="Pictures/Marvel-logo-880x660.crop.png">
</logo>
</header>
<!--The Top Navigation Menu-->
<div id="mainNav">
<ul>
<li class="current"><a href="#">Home</a></li>
<li><a href="#firstArticle">Characters</a></li>
<li><a href="#secondArticle">Movies</a></li>
<li><a href="#thirdArticle">More Info</a></li>
</ul>
</div>
</section>
//Smooth Scrolling in Main Nav
$(document).ready(function() {
$('#mainNav li a').click(function(e) {
var targetHref = $(this).attr('href');
$('html, body').animate({
scrollTop: $(targetHref).offset().top
}, 1000);
e.preventDefault();
});
});
// Sticky Header
window.onscroll = function() {
myFunction()
}; // When the user scrolls the page
var header = document.getElementById("sectionHome"); // Get the header and top nav
var sticky = header.offsetTop; // Get the offset position of the navbar
function myFunction() { // Add the sticky class to the header when you reach its scroll position. Remove "sticky" when you leave the scroll position
if (window.pageYOffset > sticky) {
header.classList.add("sticky");
} else {
header.classList.remove("sticky");
}
}
这是我尝试过的一件事,但它禁用了我的粘性标题:
$(document).ready(function() {
var headerHeight = $('header').outerHeight(); // Target your header navigation here
$('#main-nav li a').click(function(e) {
var targetHref = $(this).attr('href');
$('html, body').animate({
scrollTop: $(targetHref).offset().top - headerHeight // Add it to the calculation here
}, 1000);
e.preventDefault();
});
});
我想我可以为总标题大小设置一个值并以这种方式定位它,尽管它会禁用粘性标题。我该如何正确执行此操作?
这是我的网页: http://www.student.city.ac.uk/~aczc972
最诚挚的问候, 丹妮尔
最佳答案
我添加了一个沙箱,如何使用 jQuery 来做到这一点,一般来说,我的网站中只有一个添加内容是我正在检查目标是什么,例如滚动到首页,如果是,我正在为其运行指定的代码:
if (targetHref === "#") {
$("html, body").animate(
{ scrollTop: 0 },
"1000"
);
} else {
$("html, body").animate({scrollTop: $(targetHref).offset().top},1000);
}
减去标题高度滚动以防止标题覆盖内容
scrollTop: $(targetHref).offset().top - 180"
关于javascript - 我的粘性标题覆盖具有平滑滚动效果的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55455445/