javascript - 仅在特定页面中滚动显示 div

标签 javascript jquery

简单地说,我的主页与其他页面的一个主要不同之处是,只有向下滚动 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/

相关文章:

javascript - 服务器端数据表搜索框样式

在redirect_to之后没有调用javascript

javascript - 当页面上出现特定单词时,如何让 Tampermonkey 用户脚本播放声音?

javascript - 如何检查函数是否有参数

javascript - 为什么 Chrome 在 (.1).toString(3) 的点后生成 1099 位数字?

javascript - 让 LocalStorageProxy 与 TreeStore 一起工作

Javascript 和 CSS FOUC 防止干扰打印样式表

javascript - Jquery UI Range Slider - 将数字转换为货币

javascript - 获取div的div的文本

javascript - 保持浏览器处于加载状态直到 onLoad/Ajax 结束