代码之家  ›  专栏  ›  技术社区  ›  Flemming

如何将每行文本调整为相同的宽度-并适合div?

  •  0
  • Flemming  · 技术社区  · 6 年前

    这是 fiddle

    .divtext {
      display: table;
      font-family: impact;
      font-size: 4vw;
    }
    
    <div id="container">
      <div class="divtext">THIS IS JUST AN</div>
      <div class="divtext">EXAMPLE</div>
      <div class="divtext">TO SHOW YOU WHAT</div>
      <div class="divtext">I WANT</div>
    </div>
    
    function changeSize(){
        var els = document.getElementsByClassName("divtext"),
        refWidth = els[0].clientWidth,
        refFontSize = parseFloat(window.getComputedStyle(els[0],null).getPropertyValue("font-size")),
        i = 1;
        while(!!els[i]){
          els[i].style.fontSize = refFontSize * refWidth / els[i].clientWidth + "px";
          i++;
        }
    }
    
    $(window).resize(function(){
            changeSize();
    
    });
    

    enter image description here ... 可调整大小。

    3 回复  |  直到 6 年前
        1
  •  0
  •   Nitha    6 年前

    您可以通过添加限制来改进window.resize事件。

    https://jsfiddle.net/s8xL7d1p/

    $(window).resize(function(){
      window.addEventListener('resize', function() {
          // only run if we're not throttled
        if (!throttled) {
          // actual callback action
          changeSize();
          // we're throttled!
          throttled = true;
          // set a timeout to un-throttle
          setTimeout(function() {
            throttled = false;
          }, delay);
        }  
      });  
    });
    

    请参考 http://bencentra.com/code/2015/02/27/optimizing-window-resize.html

        2
  •  0
  •   Devin    6 年前

    display: table 摆脱闪烁。

        3
  •  0
  •   tong_gong    6 年前
    var els = document.getElementsByClassName("divtext")
    var refWidth = els[0].clientWidth
    var refFontSize = parseFloat(window.getComputedStyle(els[0], null).getPropertyValue("font-size"))
    function changeSize() {
      i = 0
      while (!!els[i]) {  
        els[i].style.fontSize = refFontSize * refWidth / els[i].clientWidth + "px";
        i++;
      }
    }
    window.resize = changeSize