1. 程式人生 > >JS怎麽計算html標簽裏文字的寬度

JS怎麽計算html標簽裏文字的寬度

nowrap proto ext mil asdf min class size clas

方法: 做一個空的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"
            });
          ruler.text(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"
        });
        ruler.text(this);
        return ruler.width();
    }
    var text = "tasdfasdfasdfest";
    var len = text.visualLength("16px");
    console.log(len)
</script>
</body>
</html>

  

JS怎麽計算html標簽裏文字的寬度