我正在尝试将此功能添加到我的导航栏 https://www.w3schools.com/howto/howto_js_sticky_header.asp .
区别在于我的网站在另一个名为 menu.html 的 HTML 文件中有 header ,它是使用 jquery 导入的,更准确地说是这个命令。
$(函数(){
$("#header").load("/structureFiles/menu.html");
});
此外,这个函数在一个单独的.js文件中,具有添加“粘性”栏的功能
window.onload= function(){
var topNav = document.getElementById("topMenu");
var sticky = topNav.offsetTop;
console.log("top menu: " + sticky);
}
当我尝试使用 getElementById
检索元素时,我得到
无法读取 null 的属性“offsetTop”
。
另一方面,如果我尝试将 jquery 与 $(window).scroll
一起使用,元素偏移量始终为零。有什么想法吗?
最佳答案
你有没有试过这样的事情:
$(window).scroll(function(){
$("#header").css(
{
position: $("#header").offset().top - window.scrollY > window.scrollY ?
"fixed" : "static",
top: 0
});
});
关于javascript - 更新使用 jQuery 检索的另一个 HTML 文件中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48737395/