網站首頁 編程語言 正文
在日常開發中,我們經常需要判斷目標元素是否在視窗之內或者和視窗的距離小于一個值(例如 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
)
},
}
原文鏈接:https://blog.csdn.net/qq_42690194/article/details/125009812
相關推薦
- 2022-12-23 Kotlin標準函數與靜態方法基礎知識詳解_Android
- 2023-10-28 go帶緩沖chan實現消息隊列功能_Golang
- 2022-07-15 教你docker方式部署nacos_docker
- 2022-10-21 Android基于Mapbox?V10?繪制LineGradient軌跡_Android
- 2022-06-18 Elasticsearches之python使用及Django與Flask集成示例_python
- 2022-10-07 Android?drawFunctor?原理及應用詳情_Android
- 2022-07-22 mybatis源碼之集成spring原理詳解
- 2022-10-05 Numpy中Meshgrid函數基本用法及2種應用場景_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支