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>
本文探讨了不同浏览器下CSS像素的解析差异,详细介绍了如何通过多种方法精确获取元素的宽度和高度,包括使用window.getComputedStyle、object.getBoundingClientRect及jQuery,同时提供了一个获取字符串显示尺寸的实用函数。
1353

被折叠的 条评论
为什么被折叠?



