js獲取dom元素寬高的幾種方法
① dom.style.width / height
這種?法,有?定局限性,只能取內(nèi)聯(lián)樣式的寬?。
<div id="id" style="height: 100px"></div>
<script>
var d = document.getElementById('id').style.height
console.log(d)
</script>② dom.currentStyle.width / height
這種?法,也是有?定局限性,不過我們?nèi)N常?css樣式都能獲取。但是只?持 IE ,其它瀏覽器不?持
③ window.getComputedStyle(dom).width / height
var d = document.getElementById('id')
console.log( window.getComputedStyle(d).height)?持所有瀏覽器,兼容性好
④ dom.getBoundingClientRect().width / height
這種?法,?般?于計算元素的絕對位置,根據(jù)視窗左上?的點來算的??梢阅玫剿膫€元素值: left 、 top 、 width 、 height
<style>
#id{
height: 100px;
width: 100px;
margin-left: 20px;
margin-top: 20px;
}
</style>
<body>
<div id="id"></div>
<script>
// 只支持內(nèi)聯(lián)樣式
// var d = document.getElementById('id').style.height
// console.log(d)
//都支持,兼容性好
// var d = document.getElementById('id')
// console.log( window.getComputedStyle(d).height)
var d = document.getElementById('id')
console.log(d.getBoundingClientRect())
</script>
</body>
總結(jié)
到此這篇關(guān)于js獲取dom元素寬高的幾種方法的文章就介紹到這了,更多相關(guān)js獲取dom元素寬高內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
js Firefox 加入收藏夾功能代碼 兼容Firefox 和 IE
最近改用Firefox后,發(fā)現(xiàn)很多網(wǎng)站的“加入收藏”鏈接點擊無效了,后來發(fā)現(xiàn)原來是IE瀏覽器和Firefox瀏覽器的“加入收藏夾”的寫法是不同的。2009-12-12
優(yōu)化網(wǎng)頁之快速的呈現(xiàn)我們的網(wǎng)頁
優(yōu)化網(wǎng)頁之快速的呈現(xiàn)我們的網(wǎng)頁...2007-06-06
JS 組件系列之Bootstrap Table 凍結(jié)列功能IE瀏覽器兼容性問題解決方案
這篇文章主要介紹了JS 組件系列之Bootstrap Table 凍結(jié)列功能IE瀏覽器兼容性問題解決方案,需要的朋友可以參考下2017-06-06
web網(wǎng)絡(luò)安全之跨站腳本攻擊(XSS)詳解
這篇文章主要介紹了web網(wǎng)絡(luò)安全之跨站腳本攻擊(XSS)的相關(guān)資料,跨站腳本攻擊XSS是一種常見的Web安全漏洞,攻擊者通過注入惡意腳本誘使用戶執(zhí)行,可能導致竊取敏感信息或執(zhí)行惡意操作,需要的朋友可以參考下2025-03-03

