V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
ehaagwlke
V2EX  ›  问与答

Chrome newtab里测量文字宽度的实现方法

  •  
  •   ehaagwlke · 2012-05-05 00:08:06 +08:00 · 4403 次点击
    这是一个创建于 4407 天前的主题,其中的信息可能已经有所发展或是发生改变。
    看Chrome的newtab页里,有一个测量文字宽度的实现方法,具体的代码在下面。
    想请教的是,pxWidth里的那个measuringDiv.clientWidth * 1.15 里的1.15是怎么来的,谢谢!

    /**
    * Fills in an invisible div with the 'Most Visited' string so that
    * its length may be measured and the nav dots sized accordingly.
    */
    function measureNavDots() {
    var measuringDiv = $('fontMeasuringDiv');
    measuringDiv.textContent = localStrings.getString('mostvisited');
    var pxWidth = Math.max(measuringDiv.clientWidth * 1.15, 80);

    var styleElement = document.createElement('style');
    styleElement.type = 'text/css';
    // max-width is used because if we run out of space, the nav dots will be
    // shrunk.
    styleElement.textContent = '.dot { max-width: ' + pxWidth + 'px; }';
    document.querySelector('head').appendChild(styleElement);
    }
    2 条回复    1970-01-01 08:00:00 +08:00
    keakon
        1
    keakon  
       2012-05-05 17:33:42 +08:00   ❤️ 1
    其实不是测量文字宽度。这个元素是position: absolute的,会正好包围文字,所以clientWidth就是文字宽度。那个1.15只是为了留点空白。
    ehaagwlke
        2
    ehaagwlke  
    OP
       2012-05-06 15:19:06 +08:00
    @keakon 从注释里看,应该是用来测量不同语言下“Most Vistied”这个字符串的宽度的。
    那个1.15应该是为了让整个button的宽度有留白。 歇息!
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1135 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 18:38 · PVG 02:38 · LAX 11:38 · JFK 14:38
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.