jsjq滚动到底部|js/jq滚动到一定位置后固定显示

更新时间:2018-03-21    来源:js教程    手机版     字体:

【www.bbyears.com--js教程】

js滚动到一定位置后固定显示

 代码如下

<script type="text/javascript">
function htmlScroll()
{
 var top = document.body.scrollTop ||  document.documentElement.scrollTop;
 if(elFix.data_top < top)
 {
  elFix.style.position = "fixed";
  elFix.style.top = 0;
  elFix.style.left = elFix.data_left;
 }
 else
 {
  elFix.style.position = "static";
 }
}

function htmlPosition(obj)
{
 var o = obj;
 var t = o.offsetTop;
 var l = o.offsetLeft;
 while(o = o.offsetParent)
 {
  t += o.offsetTop;
  l += o.offsetLeft;
 }
 obj.data_top = t;
 obj.data_left = l;
}

var oldHtmlWidth = document.documentElement.offsetWidth;
window.onresize = function(){
 var newHtmlWidth = document.documentElement.offsetWidth;
 if(oldHtmlWidth == newHtmlWidth)
 {
  return;
 }
 oldHtmlWidth = newHtmlWidth;
 elFix.style.position = "static";
 htmlPosition(elFix);
 htmlScroll();
}
window.onscroll = htmlScroll;

var elFix = document.getElementById("fixedRight");
htmlPosition(elFix);

</script>

jQuery 当元素滚动到顶部后固定位置

 代码如下

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function() {
    var elm = $("#pordAttr");
    var startPos = $(elm).offset().top;
    $.event.add(window, "scroll", function() {
        var p = $(window).scrollTop();
        $(elm).css("position",((p) > startPos) ? "fixed" : "static");
        $(elm).css("top",((p) > startPos) ? "0px" : "");
    });
});
</script>

元素滚动到顶部后固定位置

 

页面滚动时固定侧边栏效果

需要按各自的需求修改相应代码,完整的JavaScript代码如下:

 代码如下

//固定tag cloud
jQuery(function () {
    //指定的高度,侧边栏距顶部距离+侧边栏高度+可视页面的高度
    var sideTop=jQuery("#sidebar").offset().top+jQuery("#sidebar").height()+jQuery(window).height();
    var scTop = function() {
    if( typeof window.pageYOffset != "undefined") {
        return window.pageYOffset;
    } else if( typeof document.compatMode != "undefined" && document.compatMode != "BackCompat") {
        return document.documentElement.scrollTop
    } else if( typeof document.body != "undefined") {
        return document.body.scrollTop;
    }
}

jQuery(window).scroll(function() {
        if (scTop() > sideTop) {
        if(jQuery("#fixed-siderbar").length == 0){
            //下面是要显示的模块,复制侧边栏中的标签云内容,追加到侧边栏的底部
            var tag = jQuery("#tag_cloud-2 .widget-wrap").clone().html();
            var html=""+ tag +""
            jQuery("#sidebar").append(html);
        }else{
            jQuery("#fixed-siderbar").show();
        }
    }else{
        jQuery("#fixed-siderbar").hide();
    };
  });
});

最后附上我的CSS,同样按需修改

 代码如下 #fixed-siderbar{
    z-index: 0;
    position:fixed;
    top:70px;
}

效果如下

jQuery实现页面滚动时固定侧边栏效果

本文来源:http://www.bbyears.com/wangyezhizuo/40078.html

热门标签

更多>>

本类排行