简单地说,我的主页与其他页面的一个主要不同之处是,只有向下滚动 400 像素后,标题才会显示。在任何其他页面中,它都会在加载时显示,并且滚动并不重要。
我为每项工作编写了两段代码,其中一段是 jQuery,另一段是 Plain JS。我需要将它们组合起来,因为它们只应该基于“主页”条件和 y >= 400 条件工作。
这就是我所拥有的:
我的主页以编程方式添加了“home”类,因此我可以将其用作 Hook 类。
jQuery(document).ready(function($) {
//this hides the header until after slider has loaded on the homepage. Otherwise I get a glitch because the header attempts to load before the slider. So, I'm slowing it down only on the home page, else, timeout is Zero = show right away.
if ($("body").hasClass("home")){
setTimeout(function() {
$('header').removeClass("hide-header");
}, 5000);
} else {
setTimeout(function() {
$('header').addClass("show-header");
}, 0);
}
});
这是滚动的JS函数。因为它不以主页为条件,所以它正在全局范围内发生。我需要以某种方式将这两者结合起来,以便滚动的事情只发生在主页中
//show header on scroll
topHeader = document.getElementById("masthead");
var myScrollFunc = function () {
var y = window.scrollY;
if (y >= 400) {
topHeader.className = "site-header show-header"
} else {
topHeader.className = "site-header hide-header"
}
};
window.addEventListener("scroll", myScrollFunc);
如果有帮助,这里是相关的 HTML:
<body class="home page-template">
<div id="page" class="hfeed site">
<a class="skip-link screen-reader-text" href="#content">Skip to content</a>
<header id="masthead" class="site-header" role="banner">
....
</header>
.... blah blah blah
</body>
以及您在此处看到的类的 CSS
.site-header{
width: 100%;
position: fixed;
z-index: 1;
}
.hide-header {
opacity:0;
}
.show-header {
opacity:1;
}
提前谢谢大家!
最佳答案
只需在 if ($("body").hasClass("home"))
条件内添加 window.addEventListener("scroll", myScrollFunc);
.
关于javascript - 仅在特定页面中滚动显示 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42448982/