在做一些页面效果、提升用户体验等需求时,常常需要找准该效果的触发时机,而 BOM窗口 正是一个很好的触发基准点。有必要对其进行详细的整理。
jquery 的BOM窗口位置大小
jquery的高度/宽度/滚动/偏移量
窗口:
浏览器可视区域的高度:$(window).height();
浏览器可视区域的宽度:$(window).width();
文档:
页面文档高度:$(document).height();
页面文档宽度:$(document).width();
滚动:
滚动条已滚动的上距离:$(document).scrollTop();
滚动条已滚动的左距离:$(document).scrollLeft();
#demo
的页面文档的绝对偏移量, 指#demo
的实际尺寸(不含 margin )的上边界到页面顶端的距离.该值不随窗口滚动而改变:
$('#demo').offset().top;
$('#demo').offset().left;
容器各种高度所指:
1234$('#demo').height(); //content 的高度$('#demo').innerHeight(); //content+padding 的高度$('#demo').outerHeight(); //content+padding+border 的高度$('#demo').outerHeight(true); //content+padding+border+margin 的高度
jquery bom demo
滚动条离开/到达顶部,改变 fixed 顶部导航的样式
123456789101112$(window).on('scroll',function(){if($(window).scrollTop()>100){$('#head').removeClass('head-first').addClass('head-second');$('#head-logo img').attr("src","images/logo1.png");}else{$('#head').removeClass('head-second').addClass('head-first');$('#head-logo img').attr("src","images/logo2.png");}//根据 scrollTop 滚动变化、计算背景透明度渐变$('#head-box').css("background-color","rgba(247, 247, 247,"+$(window).scrollTop()/125+")");});
判断滚动条是否到达底部,下拉滚动到底部时异步加载更多数据:
123456789$(window).on('scroll',function(){//发现 $(window).scrollTop() 在PC端、移动端,总是有着小数点的的一丝差别,所以给它 +2;或者直接向上取整 Math.ceil()if($(document).height()-$(window).height() <= $(window).scrollTop()+2){alert('到达底部!');}if($(document).height()-$(window).height() == Math.ceil($(window).scrollTop())){alert('到达底部!');}});
判断元素在视口的出现和消失,对其执行相应的动作动画:
12345678910111213141516//判断元素向上滚动,是否超出滚动区域,true,超出:var isTop=$(window).scrollTop()>($('.demo').offset().top+$('.demo').outerHeight());//判断元素向下滚动,是否超出滚动区域,true,超出:var isBottom=$(window).scrollTop()<($('.demo').offset().top-$(window).height());//终上俩所述,判断是否在视口内:$(window).on('scroll',function(){var notIn=($(window).scrollTop()>($(".demo1").offset().top-50+$(".demo1").outerHeight()))||(($(window).scrollTop()+$(window).height())<$(".demo1").offset().top);if(notIn){$('.demo1').removeClass('animated fadeInLeft');}else{$('.demo1').addClass('animated fadeInLeft');}});
JavaScript 的BOM窗口位置大小
offset
5个:offsetParent
;offsetTop
、offsetLeft
;offsetWidth
、offsetHeight
。
说明:
- obj.offsetWidth 是指 obj 自身的绝对宽度,不含 overflow 隐藏的部分,整型,单位像素。
- obj.offsetTop 是指 obj 相对于版面或由 offsetParent 属性指定的父坐标的上侧位置,整型,单位像素。
- offsetParent 属性返回一个对象的引用,这个对象是距离调用offsetParent的元素最近的、且是已CSS定位过的父级容器元素;如果当前元素的父级元素没有进行CSS定位(position为absolute或relative),offsetParent为body。
scroll
scrollHeight
:元素的padding加元素内容的高度,这个高度与滚动条无关,是元素的实际高度(滚动高度)。scrollWidth
:元素的滚动宽度,理解同上。scrollLeft
:设置/获取位于 元素左边界 和 窗口中可见内容的最左端 之间的距离。scrollTop
:设置/获取位于 元素最顶端 和 窗口中可见内容的最顶端 之间的距离。
client
clientHeight/clientWidth
: 对象可见的高度/宽度,会随着窗口大小的改变而改变。clientLeft/clientTop
: 返回 对象的offsetLeft属性值 和 到当前窗口左边的真实值 之间的距离,可以理解为边框的长度。
offsetTop/style.top
- offsetTop 返回的是数字,style.top 返回的是字符串(数字+px) 。
- offsetTop 只读,style.top 可读可写。
- 若元素没定义过 top 样式,style.top 返回空字符串。
- 同理,offsetLeft/style.left、offsetWidth/style.width、offsetHeight/style.height。
BOM在不同的浏览器之间还有着不一样解析,兼容性……呜呜。