TOP

jQuery判断div随滚动条滚动到一定位置后停止

发布时间:2025-09-02 17:24:56

var rollSet = $('#widget');
    var offset = rollSet.offset();
    var fwidth = $("#footer").height();
    $(window).scroll(function() {
        var scrollTop = $(window).scrollTop();
        var scrollBtm = $(document).height() - $(window).scrollTop() - $("#widget").height();
        if (offset.top < scrollTop) {
            if (scrollBtm > fwidth) {
                rollSet.removeClass('absolute').addClass('fixed')
            } else {
                rollSet.removeClass('fixed').addClass('absolute')
            }
        } else {
            rollSet.removeClass('fixed')
        }
    })

方法说明:
由页面总高度减去已滚动的高度再减去ID为widget的层的高度即等于该层底部距离底部的高度;
当距离底部的高度小于或等于特定位置距离底部的高度时,去掉样式fixed,然后给该层添加绝对定位!
CSS中要给父父层添加position:relative;

以下是自写的
style css:
<!--
.goods_title_line{
width:880px;
height:20px;
background-color:#DFFFFF;
margin-top:1px;
border-top-width: 2px;
border-top-color: #009999;
border-top-style: solid;
border-bottom-width: 1px;
border-bottom-style: solid;
border-bottom-color: #E6E6E6;
font-size:13px;
}
-->

$(document).ready(function(){
var goods_title_line_document_scroll=$(".goods_title_line").offset();
var goods_title_line_document_scroll_height=goods_title_line_document_scroll.top;
$(document).scroll(function(){
var a=$(document).scrollTop();
if(a>goods_title_line_document_scroll_height){
$(".goods_title_line").css({"position":"fixed","top":"0","z-index":"100"});
}else{
$(".goods_title_line").css("position","static");
}
});
});