100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > Js 精确获取Dom元素宽度/高度

Js 精确获取Dom元素宽度/高度

时间:2023-06-14 01:23:42

相关推荐

Js 精确获取Dom元素宽度/高度

css像素解析:

四舍五入解析的浏览器:IE8、IE9、Chrome、Firefox

直接取整解析的浏览器:IE7、Safari

获取元素精确的宽度/高度(带小数位像素)

问题:document.getElementById(id).style.width 只能获取元素行内样式的值

解决办法一:

window.getComputedStyle(element) 返回元素所有CSS属性值

解决办法二:

object.getBoundingClientRect() 返回元素的大小及其相对于视口的位置

解决办法三:

jQuery $(obj).width();

<!DOCTYPE html><html lang="zh"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no,viewport-fit=cover"><title>demo</title><style>*{margin: 0;padding:0;}#fir{display: inline-block;width: 74px;font-size: 16px;background-color: red;}#sec{display: inline-block;font-size: 16px;background-color: red;}</style></head><body><span id="fir">测试 测试!</span><br/><span id="sec">测试 测试!</span><script src="../resource/jquery-3.3.1.min.js"></script><script>/*获取元素精确的宽度/高度(带小数位像素)*/let firWidth = document.getElementById('fir').style.width; console.log('firWidth:'+firWidth); // firWidth: "" 无法获取元素的宽度let secWidth = $('#sec').width(); console.log('secWidth:'+secWidth); // secWidth: 73.7344 只能获取元素像素整数部分的值let secObj = document.getElementById('sec');let secWidth2 = window.getComputedStyle(secObj).width;console.log('secWidth2:'+secWidth2); // secWidth2: 73.7344px 精确获取元素像素值(带像素单位)let secWidth3 = secObj.getBoundingClientRect().width;console.log('secWidth3:'+secWidth3); // secWidth3: 73.734375 精确获取元素像素值/*获取字符串显示的宽度/高度*/function getEleSize(fontSize,fontFamily,conent){let spanObj = document.createElement('span');let result = {};spanObj.style.fontSize = fontSize;spanObj.style.fontFamily = fontFamily;spanObj.style.visibility = "hidden";spanObj.style.display = "inline-block";document.body.appendChild(spanObj);spanObj.textContent = conent;result.width = parseFloat(window.getComputedStyle(spanObj).width);result.height = parseFloat(window.getComputedStyle(spanObj).height);return result;}let eleWidth = getEleSize('16px','','测试 测试!').width; console.log('eleWidth:'+eleWidth); // 可与 #sec 对比</script></body></html>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。