/*几个必须的参数*/
/*窗口的高度 - div距离顶部的距离(offset().top - scrollTop) - div的高度 = 该div底部 距离窗口的底端的距离*/
/*div距离 顶部 的距离 + div的height = div 底部 距离窗口顶部的距离*/
/*底部距离窗口上端的距离 <= 窗口的高度*/
/*图片和窗口高度之间的留白(用来计算距离底部的距离时用作滚动效果) = 窗口高度 - 图片高度 - 图片间隙 - 顶部固定条高度*/
/*窗口的高度 - div距离顶部的距离(offset().top - scrollTop) - div的高度 = 该div底部 距离窗口的底端的距离=图片距离低端的距离*/
minHeight = fixAd_pic1.height() + fixAd_pic2.height() + fixAd_pic3.height() + 30 + 3*15, /*图片高度 + 间隙高度 + 顶部浮动条高度*/
maxHeight = fixAd_pic1.height() + fixAd_pic2.height() + fixAd_pic3.height() + 80 + 30 + 4*15 , /*80 footer的高度 15 间隙距离 30 顶部浮动条的距离*/
windowHeight = $(window).height(); //窗口高度
news_list = $("#news_list"); //以该节点为基点
news_listTop = news_list.offset().top,
documentScroll = documentEle.scrollTop(), //滚动条距离顶端高度
/*div距离最低端的距离 = 图片最下边时的距离*/
bottom = windowHeight - news_list.height() - (news_listTop - documentScroll);
//基线底端距离窗口顶端的高度
as = news_listTop - documentScroll + news_list.height(),
//图片下端距离底部的距离
bs = windowHeight - fixAd_pic3.height() - fixAd_pic2.height() - fixAd_pic1.height() - 30 - 45;
/* 窗口高度大于图片高度 小于图片+顶部底部的高度 判断图片合适做固定开始向上向下改变位置*/
if((as + bs) <= windowHeight){
fixAd_pic3.css({"top": "auto", "bottom": bottom + 15 + "px"});
fixAd_pic1.css({"top": "auto", "bottom": bottom + 15 + 270 + 15 + "px"});
}else{
fixAd_pic3.css({"top": "", "bottom": "auto"});
fixAd_pic1.css({"top": "", "bottom": "auto"});
}
/*窗口高度小于 440*/
/*if((news_listTop - documentScroll + news_list.height() + (windowHeight - fixAd_pic3.height() -fixAd_pic1.height())) <= windowHeight){*/
/* 改为下边这种*/
if (windowHeight <= minHeight) {
fixAd_pic3.css({"top": "auto", "bottom": bottom + "px"});
fixAd_pic1.css({"top": "auto", "bottom": bottom + 270 + 15 + "px"});
}else{
fixAd_pic3.css({"top": "", "bottom": "auto"});
fixAd_pic1.css({"top": "", "bottom": "auto"});
}
ps:在滚动效果中过去到某个div的高度$(".div").height() 与直接在页面加载完成后就获取高度存在差异,目前不清楚为什么,待解决即: var divHeight1 = $(".div").height();与: $(document).scroll(function(){var divHeight2 = $(".div").height();/* divHeight1 不等于 divHeight2 */});
刚发现一个css3的一个属性 position:sticky;这个就可以直接实现以上功能,简单实用,而且不需要经过繁杂的计算
div{
position: sticky; /*如果偏移量不超过下边预设值,这个效果是relative,超过就是fixed的效果*/
top: 0px; /*此处是,如果该div偏移超过这个值,就会浮动起来固定在浏览器顶部位置上*/
}