我不明白为什么这段代码不能正常工作:
$(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 - shop-cart 的 div 和里面的一些 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>
关于javascript - 如何使用 JS 添加和删除 CSS 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42168866/