tnblog
首页
视频
资源
登录

js、JQuery获取文本的宽高

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

页面编写:

<!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()获取会精确不到小数点后



评价
Decorating heart
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
欢迎加群交流技术