【问题标题】:How to find the width of text rendered by the DOM?如何找到 DOM 呈现的文本的宽度?
【发布时间】:2018-02-05 00:40:09
【问题描述】:

我正在尝试查找 HTML 呈现的文本的宽度。这是一个问题:

https://jsfiddle.net/ebytzdmv/

不起作用的关键代码行:

var textWidth = $("#text").width();

我不知道为什么这段代码没有给我一个与该文本宽度相同的数字。我需要它来确保我的网页将显示的文本始终与某个图像的宽度相同,即使文本是动态的(计时器)并且可以更改。

【问题讨论】:

  • div 默认来自显示类型“block”,因此它们具有适合父级的最大宽度。您需要使用“内联”或“内联块”显示样式。

标签: jquery html text width


【解决方案1】:

这是因为您没有在页面上添加 jquery 并且您尝试使用 $ 使用 jquery,您的代码抛出 $ 未定义的错误..

Kindly add jquery in the head of your application.

下面是您的代码的工作 HTML。

 <!DOCTYPE html>
<html>
<head>
<style>
#text {
  position: relative;
  color: #81a136;
  font-size: 50px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
   try{
        var textWidth = $("#text").width();
      }
      catch(e)
      {
        alert(e);
      }
        document.getElementById('answer').innerHTML = textWidth
});
</script>
</head>
<body>

<div id="text">
  Hi, I have a width.
</div>

<div id="answer">

</div>

</body>
</html>

【讨论】:

  • 如果这有帮助,请将其标记为答案。带有绿色小勾号图标。
猜你喜欢
  • 2021-10-09
  • 2018-09-03
  • 2020-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-17
  • 1970-01-01
相关资源
最近更新 更多