javascript - 带有平滑滚动效果的粘滞标题封面内容
问题描述
我添加了一个粘性标题和平滑的滚动效果,但我无法弄清楚如何固定位置,因此它与标题大小有关。我尝试过的东西完全禁用了粘性标题。
我尝试使用几种不同的技术,尽管我是新手,我自己可能很难做到。
<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"
推荐阅读
- macros - 宏数值比较
- javascript - 更改只读输入值
- javascript - 如何强制组件在同步请求之间重新渲染?(反应原生)
- excel - 如何从表中选择除标题之外的所有项目?
- r - 我该如何解决这个 t 检验错误 - 它说“数据基本上是恒定的”?
- c++ - (Qt with C++)读取文件(~25Mb)并比较字符串比python慢
- html - 带有垂直列文本的引导表样式
- three.js - THREE.js:如何在忽略材质颜色的情况下更改面的颜色?
- android - Flutter,根据屏幕分辨率/dpi优化材料尺寸的最佳方法?
- python - 如何在散景中设置字形的悬停颜色?