我正在为一个网站制作主题,并且获得了使用 HTML 文件的权限。问题是我只是熟悉 CSS 和 HTML,但在 Javascript、JQuery 等方面我完全是个菜鸟,遗憾的是,我似乎需要这些来添加我想要的一些功能。
我想要一个像这样工作的菜单:https://www.planetside2.com/news
HTML 基本上是这样的:
<div id="wrap">
<div id="page-header">
<div class="headerbar">
</div>
</div>
里面还有很多东西,但我希望容器够用
这是 CSS:
#wrap {
margin: 0 auto;
width: 1024px;
}
.headerbar {
background: url("{T_THEME_PATH}/images/headerbarbg.png") no-repeat ;
background-position: center;
width: 1054px;
margin:0 -15px;
margin-top:3px;
height: 120px;
position: relative;
padding-top: 70px;
}
我已经检查了一些其他的解决方案,但是,正如我所说,我是一个完全的脚本编写新手,当我尝试将此类脚本应用于主题时,它们不起作用,很可能是因为有一些我不知道应该更改的内容(当然,类和 ID 除外)。
我希望有人能帮助我。
最佳答案
首先你需要检测滚动和窗口大小调整
$(document).ready(function(){
$(window).on("scroll resize", function(e){
var elem = $(".headerbar");
// check if your header is visible by subtracting
// the top offset of your div from the scrolltop distance
if ((elem.offset().top - $(window).scrollTop()) <= 0 && elem.css("position") !== "fixed") {
console.log("not visible");
elem.css({
position:"fixed",
"z-index":"9999",
top:"0px"
});
// check if your header height is greater or equal to the scrolltop distance
} else if (elem.height() >= $(window).scrollTop()) {
console.log("visible");
elem.css({
position:"relative"
});
}
});
})
这是一个简单的演示:JSFIDDLE
关于javascript - 发生滚动后,如何使 div(菜单)固定位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25721602/