我有一个 div 元素,当网页加载并放置在其他 div 元素之间时,该元素是否可见。这是代码示例:
<style>
.block {
width: 100%;
height: 500px;
/* Height will be dynamic. It's just to test when element is not visible on initial view */
background: yellow;
}
.sticking-block {
width: 100%;
height 30px;
/* Height will be dynamic */
background: red;
}
.sticking-block.sticky {
position: fixed;
bottom: 0;
width: 100%;
z-index: 999;
}
</style>
<div class="block">some content
</div>
<div class="block">some content
</div>
<div class="block">some content
</div>
<div class="block">some content
</div>
<div class="sticking-block">this block sticks to the bottom
</div>
<div class="block">some content
</div>
<div class="block">some content
</div>
所以我想添加类“.sticky”,当浏览器窗口底部到达“.sticking-block”元素的底部并在滚动到网页底部时保持它固定。或者在再次向上滚动并到达元素的前一个位置时删除“.sticky”类。“.sticking-block”在初始视图中可见或不可见,取决于“.block”元素的高度。
当然,这是一些高度计算。感谢帮助。
您可以使用 jQuery 轻松完成此操作。这是解决方案。请检查。
<html>
<head></head>
<body>
<style>
.block {
width: 100%;
height: 500px;
/* Height will be dynamic. It's just to test when element is not visible on initial view */
background: yellow;
}
.sticking-block {
width: 100%;
height 30px;
/* Height will be dynamic */
background: red;
}
.sticking-block.sticky {
position: fixed;
bottom: 0;
width: 100%;
z-index: 999;
}
</style>
<div class="block">some content
</div>
<div class="block">some content
</div>
<div class="block">some content
</div>
<div class="block">some content
</div>
<div class="sticking-block">this block sticks to the bottom
</div>
<div class="block">some content
</div>
<div class="block">some content
</div>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script>
var $sticky = $('.sticking-block');
var stickytop = $sticky.offset().top;
$(window).scroll(function(){
var scroll = $(window).scrollTop() + $(window).height();
if (scroll >= stickytop) $sticky.addClass('sticky');
else $sticky.removeClass('sticky');
});
</script>
</body>
</html>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句