tnblog
首页
视频
资源
登录

js、JQuery获取文本的宽高

6369人阅读 2019/4/18 15:59 总访问:144536 评论:1 收藏:0 手机
分类: 前端

页面编写:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4.     <meta charset="UTF-8" />
  5.     <title>jQuery获取文本宽度、高度</title>
  6.     <script src="Scripts/jquery-3.3.1.js"></script>
  7. </head>
  8. <body>
  9.     <span id="txt" style="display: inline-block;">Hello!剑哥!</span>
  10. </body>
  11. </html>

运行查看宽高:


一、第一种jQuery获取:

    输出:

  1. <script type="text/javascript">
  2.   $(function ({
  3.      console.log("jquery获取 [" + $("#txt").width() + "," + $("#txt").height() + "]:");
  4.   });
  5. </script>

    结果:

二、第二种js获取:

  1. function Size(txt{
  2.   var p = document.createElement("p");//定义一个p标签来存文本内容
  3.   var result = {};
  4.   result.width = p.offsetWidth;
  5.   result.height = p.offsetHeight;
  6.   p.style.visibility = "hidden";
  7.   p.style.display = "inline-block";
  8.   document.body.appendChild(p);
  9.   if (typeof p.textContent != "undefined") {
  10.       p.textContent = txt;
  11.   } else {
  12.       p.innerText = txt;
  13.   }
  14.   result.width = parseFloat(window.getComputedStyle(p).width) - result.width;
  15.   result.height = parseFloat(window.getComputedStyle(p).height) - result.height;
  16.   return result;
  17. }

对比调用显示效果:

  1. $(function ({
  2.   console.log("jquery获取 [" + $("#txt").width() + "," + $("#txt").height() + "]:");
  3.   var result = Size("Hello!剑哥!");
  4.   console.log("js获取 [" + result.width + "," + result.height + "]:");
  5. });


有了这个宽度我们就可以做一些页面上的事情,比如一段动态加载的文字,当文字超过固定的显示宽度后,就让其滚动显示,就不会出现看不完整的情况


PS:有发现jQuery低版本用width()获取会精确不到小数点后



评价

尘叶心繁

2025/1/10 15:50:49

[good]

Decorating heart
排名
158
文章
3
粉丝
0
评论
1
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术