
页面编写:
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8" />
- <title>jQuery获取文本宽度、高度</title>
- <script src="Scripts/jquery-3.3.1.js"></script>
- </head>
- <body>
- <span id="txt" style="display: inline-block;">Hello!剑哥!</span>
- </body>
- </html>
运行查看宽高:
一、第一种jQuery获取:
输出:
- <script type="text/javascript">
- $(function () {
- console.log("jquery获取 [" + $("#txt").width() + "," + $("#txt").height() + "]:");
- });
- </script>
结果:
二、第二种js获取:
- function Size(txt) {
- var p = document.createElement("p");//定义一个p标签来存文本内容
- var result = {};
- result.width = p.offsetWidth;
- result.height = p.offsetHeight;
- p.style.visibility = "hidden";
- p.style.display = "inline-block";
- document.body.appendChild(p);
- if (typeof p.textContent != "undefined") {
- p.textContent = txt;
- } else {
- p.innerText = txt;
- }
- result.width = parseFloat(window.getComputedStyle(p).width) - result.width;
- result.height = parseFloat(window.getComputedStyle(p).height) - result.height;
- return result;
- }
对比调用显示效果:
- $(function () {
- console.log("jquery获取 [" + $("#txt").width() + "," + $("#txt").height() + "]:");
- var result = Size("Hello!剑哥!");
- console.log("js获取 [" + result.width + "," + result.height + "]:");
- });
有了这个宽度我们就可以做一些页面上的事情,比如一段动态加载的文字,当文字超过固定的显示宽度后,就让其滚动显示,就不会出现看不完整的情况
PS:有发现jQuery低版本用width()获取会精确不到小数点后
评价
尘叶心繁