当前位置:首页 > 前端 > Javascript > 正文内容

【JS】判断元素是否在可视区域

virtualman1年前 (2023-03-14)Javascript2876

判断一个元素是否在可视区域,我们有通常有两种办法,第一种是:使用元素的 getBoundingClientRect 属性的 top 值和页面的 clientHeight进行对比, 如果top的值小于 clientHeight表示元素在可视区域内。这种方式的缺点是需要监听scroll事件,第二种是利用高级特性 Intersection Observer 来判断元素是否可见,这种方式不用监听scroll事件,元素可见变调用回调,在回调里面处理。

getBoundingClientRect

用法: rectObject = object.getBoundingClientRect()

返回一组用于描述元素的只读属性-lefttop,right,bottonwidthheight,除了width和height外的属性都是相当于于视口左上角而言的。bottom和right于正常的有所不同

clipboard.png

const isContain =function(dom) {
	      const totalHeight = window.innerHeight || document.documentElement.clientHeight;
	      const totalWidth = window.innerWidth || document.documentElement.clientWidth;
	      // 当滚动条滚动时,top, left, bottom, right时刻会发生改变。
				//console.log(dom)
				var obj = {}
	      try{
					obj = dom.getBoundingClientRect();
				}
				catch{
					
				}
				//console.log(obj)
				var { top, right, bottom, left }=obj;
				
	      return (top >= 56 && left >= 0 && right <= totalWidth && bottom <= totalHeight);
	    }


发表评论

访客

看不清,换一张

◎欢迎参与讨论,请在这里发表您的看法和观点。