重點:
1.在H5頁面,文字大小單位為rem
2.不同的font-family,文字的寬度不一樣
3.文字寬度同時受font-size和font-family影響
思路:
在頁面動態創建一個節點,設置節點的font-size,font-family,還有內容,然后獲取它的寬度。節點寬度必須隨內容變化而變化,所以使用display:inline-block 為了避免禪城誤差,使用 getComputedStyle 方法來計算寬度,具體原因看上一篇博客:http://blog.csdn.net/zy1281539626/article/details/78488062
廢話不多說,直接上代碼:
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Document</title> </head> <body> <!-- 此span作為對比 --> <span id="test" style="display: inline-block;font-size:20px;font-family: arial;">abcdefg</span> <script src="jquery.min.js"></script> <script> function textSize(fontSize,fontFamily,text){ var span = document.createElement("span"); var result = {}; result.width = span.offsetWidth; result.height = span.offsetHeight; span.style.visibility = "hidden"; span.style.fontSize = fontSize; span.style.fontFamily = fontFamily; span.style.display = "inline-block"; document.body.appendChild(span); if(typeof span.textContent != "undefined"){ span.textContent = text; }else{ span.innerText = text; } result.width = parseFloat(window.getComputedStyle(span).width) - result.width; result.height = parseFloat(window.getComputedStyle(span).height) - result.height; return result; } console.log(textSize("20px","Arial","abcdefg")); </script> </body> </html>
對比文字精確寬度如圖:
函數計算得到的寬度:
寬高非常精確,用這種方法就可以計算在H5頁面中當前字體字號的每個字符的寬度了,也可以一起計算長字符串的寬度。
想了解怎么計算元素精確尺寸的參考上一篇博客:http://blog.csdn.net/zy1281539626/article/details/78488062