網站首頁 編程語言 正文
在日常開發中,我們經常需要判斷目標元素是否在視窗之內或者和視窗的距離小于一個值(例如 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-04-06 聊聊c++數組名稱和sizeof的問題_C 語言
- 2022-06-23 .bat文件中start、pause、goto及rem的用法示例_DOS/BAT
- 2024-01-11 String數組轉List的三種方式
- 2022-11-26 docker安裝portainer方法詳細步驟_docker
- 2022-05-09 Python?Matplotlib條形圖之垂直條形圖和水平條形圖詳解_python
- 2022-01-02 適合初學者學習ajax表單提交的全部代碼
- 2022-06-01 C語言超詳細講解字符串相乘_C 語言
- 2023-03-02 C語言數據結構中約瑟夫環問題探究_C 語言
- 最近更新
-
- 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同步修改后的遠程分支