当窗口向下滚动到 .view
不再可见时,我一直在监视哪些 CSS 类属性应用于 .header
。 scroll-header
类已添加到 .header
,但未应用关联的 CSS 属性。他们的问题是为什么以及如何解决这个问题?
$(document).ready(function() {
console.log("script.js is detected"); //check
$(window).scroll(function() {
console.log("window onscroll being called."); //check
if ($("div.view").visible(true)) {
console.log("YES if ( $(\"div.view\").visible(true) )"); //check
$(".header").removeClass(".scroll-header");
} else {
console.log("NO if ( $(\"div.view\").visible(true) )"); //check
$(".header").addClass(".scroll-header");
}
});
});
.view {
height: 500px;
width: 100%;
background-color: crimson;
}
.second {
height: 2500px;
width: 100%;
background-color: purple;
}
.header {
position: absolute;
width: 100%;
height: 100px;
background-color: cyan;
top: 0px;
left: 0px;
}
.scroll-header {
background-color: yellow;
position: fixed;
width: 100%;
height: 70px;
background-color: yellow;
}
* {
border: 0px;
padding: 0px;
margin: 0px;
box-sizing: border-box;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.visible/1.1.0/jquery.visible.min.js"></script>
<div class="view">.</div>
<div class="header">.</div>
<div class="second">.</div>
<div class="scroll-header" style="bottom:0px;">.</div>
最佳答案
如评论中所述,.visible
不是 jquery 的函数。尽管您可以使用以下代码来检测您的 dom 元素是否可见:
if ($("#yourElem").is(":visible") == true) {
//do something
}
else {
//do something else
}
因为您正在使用 jquery.visible 插件。您的代码在 javascript 中是错误的。正确代码:
$(document).ready(function() {
console.log("script.js is detected"); //check
$(window).scroll(function() {
console.log("window onscroll being called."); //check
if ($("div.view").visible(true)) {
console.log("YES if ( $(\"div.view\").visible(true) )"); //check
$(".header").removeClass("scroll-header");
} else {
console.log("NO if ( $(\"div.view\").visible(true) )"); //check
$(".header").addClass("scroll-header");
}
});
});
您添加的是 .scroll-header 而不是 scroll-header
关于javascript - JS 在运行时将 CSS 类添加到元素,但未应用其属性。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33732318/