一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

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

时间:2022-11-14 22:02:46 编辑:袖梨 来源:一聚教程网

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

代码如下 复制代码

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);

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

代码如下 复制代码


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

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

需要按各自的需求修改相应代码,完整的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实现页面滚动时固定侧边栏效果

热门栏目