ehaagwlke
V2EX  ›  问与答

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

  •  
  •   ehaagwlke · May 5, 2012 · 5008 views
    This topic created in 5214 days ago, the information mentioned may be changed or developed.
    看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 replies    1970-01-01 08:00:00 +08:00
    keakon
        1
    keakon  
       May 5, 2012   ❤️ 1
    其实不是测量文字宽度。这个元素是position: absolute的,会正好包围文字,所以clientWidth就是文字宽度。那个1.15只是为了留点空白。
    ehaagwlke
        2
    ehaagwlke  
    OP
       May 6, 2012
    @keakon 从注释里看,应该是用来测量不同语言下“Most Vistied”这个字符串的宽度的。
    那个1.15应该是为了让整个button的宽度有留白。 歇息!
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1042 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 19ms · UTC 18:32 · PVG 02:32 · LAX 11:32 · JFK 14:32
    ♥ Do have faith in what you're doing.