[英]How to add and remove CSS classes using JS
我不明白为什么这段代码无法正常工作:
$(document).ready(function() {
$(window).scroll(function() {
console.log($(window).scrollTop())
if ($(window).scrollTop() < 626) {
$('#shop-cart').addClass('shopcart-hidden').removeClass('shopcart-fixed');
}
if ($(window).scrollTop() > 625) {
$('#shop-cart').removeClass('shopcart-hidden').addClass('shopcart-fixed');
}
});
});
想法是在页面加载时隐藏购物车信息,并仅在用户向下滚动一点时显示它。 如果用户向上滚动,则应再次隐藏该信息。 我有一个带id的div-shop-cart和其中的一些php代码,也有在style.css中定义的CSS类:
#shop-cart {
background:#757575;
}
.shopcart-fixed {
float:right;
right:0;
z-index:100;
position:fixed;
}
.shopcart-hidden {
display:none;
}
默认情况下,使用CSS隐藏该栏,然后您只需要切换一个类,即可通过指定的scrollTop()
将其显示为固定。
$(document).ready(function() { $shopCart = $('#shop-cart'); $(window).scroll(function() { var $scrollTop = $(window).scrollTop(); if ($scrollTop < 626) { $shopCart.removeClass('shopcart-fixed'); } if ($scrollTop > 625) { $shopCart.addClass('shopcart-fixed'); } }); });
body { min-height: 500vh; } .shop-cart { background:#757575; display: none; } .shopcart-fixed { right:0; z-index:100; position:fixed; display: block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="shop-cart" class="shop-cart">shop-cart</div>
jQuery.toggleClass
具有第二个参数,告诉我们是否要删除该类或添加它。 您可以像这样使用它:
$(document).ready(function() {
$(window).scroll(function() {
var scrollTest = ($(window).scrollTop() < 625); // will be true or false
$('#shop-cart').toggleClass('shopcart-hidden', scrollTest); // will add if scrollTest is true, remove otherwise
$('#shop-cart').toggleClass('shopcart-fixed', !scrollTest); // will add if scrollTest is false, remove otherwise
});
});
注意:为什么要使用两个类来完成只能使用一个类可以做的事情? 只需将一个类的CSS设置为默认值,然后在设置另一个类时覆盖该CSS。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.