JS怎么计算html标签⾥⽂字的宽度⽅法:做⼀个空的html 标签 id为“ruler”,样式为“position:absolute;visibility: hidden; white-space: nowrap;z-index: -100”;
    ⽬的为了不影响页⾯,只是⽤来放你要测的⽂字的宽度,得到⽬标⽂字的内容,⼤⼩和字体.放到如下⽅法就⾏了:
String.prototype.visualLength = function(size,family)
      {
    var ruler = $("#ruler").css({
    "font-size":size || "inherit",
  "font-family":family || "inherit"
    });
  (this);
  return ruler.width();
      }
 实例如下:
<!DOCTYPE html>
<html>
<head>
</head>
<style>
#ruler {
position:absolute;
visibility: hidden;
white-space: nowrap;
z-index: -100;
}
</style>
<body>
<span id="ruler">test</span>
<span >tasdfasdfasdfest</span>
<script src="./jquery.min.js"></script>
<script>
String.prototype.visualLength = function(size,family)
{
var ruler = $("#ruler").css({
"font-size":size || "inherit",
"font-family":family || "inherit"
});
<(this);
return ruler.width();
}
css和html和js怎么结合var text = "tasdfasdfasdfest";
var len = text.visualLength("16px");
console.log(len)
</script>
</body>
</html>

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。