使用javascript計算文本的寬度

 //這裏只能用span,不能用pre。可用
    String.prototype.getWidth = function(fontSize)
    {
        var span = document.getElementById("__getwidth");
        if (span == null) {
            span = document.createElement("span");
            span.id = "__getwidth";
            
            document.body.appendChild(span);
            //$(span).hide();
            span.style.visibility = "hidden";
            span.style.height="0px";
            span.style.whiteSpace = "nowrap";
        }
        span.innerText = this;
        span.style.fontSize = fontSize + "px";
        var offsetwidth = span.offsetWidth;
        $(span).remove();

        return offsetwidth;
    }

這裏的span不能使用pre或者div,不然會撐開頁面。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章