问题情况:“当滚动条滚动到一定scolltop值的时候去浮动或者取消浮动某些元素”我实现了这种效果,但是我将代码写死了,我指定了固定的滚动条scolltop数值,当网页内容发生
改变,比如网页内容没有那么大的scolltop值的时候,则会出现不理想的情况。所以要实现根据网页内容变化动态改变该scolltop值的效果。
解决方法:
1.获取页面的高度
2.获取浏览器能看到的那部分的高度
3.获取到达底端时的scolltop 只要获取$(document).height()-$(window).height()
4,减去你想浮动的元素离底端的高度值(因为我想浮动的元素在离底端比较近)
写死了的代码:
//滚动条事件
$(window).scroll(function() {
if($(window).scrollTop() >= 227){ //指定了scolltop值
$('.c-main-right-tootbar').addClass('fix');
}
else{
$('.c-main-right-tootbar').removeClass('fix');
}
});
代码:
//获取浏览器高度
function getWindowHeight(){
return $(window).height();
}
//获取document的高度
function getDocumentHeight(){
return $(document).height();
}
$(window).scroll(function() {
$('.txt').html("<span style='color:red;'>'"+$(window).scrollTop()+"'</span>");
if($(window).scrollTop() <= getDocumentHeight()-getWindowHeight()-148){
$('.c-footer').addClass('fix2'); //使元素浮动
}
else{
$('.c-footer').removeClass('fix2'); //取消元素浮动
}
});