搜索了半天,求出字符串的length的倒是一下就找到了,显示宽的没能找到.有没有类似delphi里的Canvs.TextWidth的函数?请各位指点,拜谢~~~

解决方案 »

  1.   

    http://topic.csdn.net/u/20070316/20/b77adc63-c440-4ede-9e5c-38bc4f2a8e97.html
      

  2.   

    先谢谢2楼的朋友提供方法,不过其中有不太明白的地方 请指点:
    ---------------------------------------------------------
    <SPAN   id=span   style= "font-size:9pt "> </span> var   o=document.getElementById( "span "); 
    var   oldWidth=o.offsetWidth; 
            o.innerText= "字符 "; 
    var   width=o.offsetWidth-oldWidth; alert(“宽:”+width)--------------------------------------------------------------
    其中的<SPAN   id=span   style= "font-size:9pt "> </span> 是怎么在JavaScript里用的?
    我加到JavaScript里后 就卡死了
      

  3.   


    明显<SPAN  id=span  style= "font-size:9pt "> </span>是html部分,不是脚本明白原理自己就可以写了,就是用span标签赋值文本计算宽度,参考如下代码:
    function textSize(fontSize, text) {
        var span = document.createElement("span");
        var result = {};
        result.width = span.offsetWidth;
        result.height = span.offsetWidth; 
        span.style.visibility = "hidden";
        document.body.appendChild(span);
        if (typeof span.textContent != "undefined")
            span.textContent = text;
        else span.innerText = text;
        result.width = span.offsetWidth - result.width;
        result.height = span.offsetHeight - result.height;
        span.parentNode.removeChild(span);
        return result;
    }var size = textSize("9px", "囧");
    alert("宽:" + size.width + " 高:" + size.height);
      

  4.   

    用div span或者甚至td存放你的文字
    js获取其width应该可以吧
      

  5.   

    function textSize(fontSize, text)第1个参数 似乎是无效的参数?没看到哪儿有用到......
      

  6.   

    那個是當你用到字體大小的時候才用的,因為字體大小會影響字符串的寬度
    //span.style.fontSize=fontSize; 沒寫上而已
      

  7.   

    var span = document.createElement("span");
    var result = {};result.width = span.offsetWidth;
    result.height = span.offsetWidth;........result.width = span.offsetWidth - result.width;
    result.height = span.offsetHeight - result.height;为什么要这么做呢?为什么不直接将text赋值给span,然后直接用赋值后的W和H呢?
      

  8.   

    3楼的代码我执行了阿,为什么不行呢,在 document.body.appendChild(span);
    总通不过呢