在日常开发中,我们经常需要判断目标元素是否在视窗之内或者和视窗的距离小于一个值(例如 100 px),从而实现一些常用的功能;
话不多说,方法有很多种,这里使用的是:getBoundingClientRect()方法
getBoundingClientRect()获取元素位置,这个方法没有参数
getBoundingClientRect()用于获得页面中某个元素的左,上,右和下分别相对浏览器视窗的位置。
getBoundingClientRect()是DOM元素到浏览器可视范围的距离(不包含文档卷起的部分)。
该函数返回一个Object对象,该对象有6个属性:top,lef,right,bottom,width,height;
html中:
<div id="box"></div>
js中:
var object = document.getElementById('box');
el= object.getBoundingClientRect();
el.top:元素上边到视窗上边的距离;
el.right:元素右边到视窗左边的距离;
el.bottom:元素下边到视窗上边的距离;
el.left:元素左边到视窗左边的距离;
el.width:是元素自身的宽
el.height是元素自身的高
直接上代码,亲测可用
mounted:{
$(window).on('scroll', () => {
console.log('scroll !')
alert(this.isInViewPort(document.getElementById('element')))
})
}
methods:{
isInViewPort (element) {
const viewWidth = window.innerWidth || document.documentElement.clientWidth || ''
const viewHeight = window.innerHeight || document.documentElement.clientHeight || ''
const {
top,
right,
bottom,
left,
} = element.getBoundingClientRect()
return (
top >= 0 &&
left >= 0 &&
right <= viewWidth &&
bottom <= viewHeight
)
},
}