从getElementById重写函数到getElementsByClassName或getElementsByTagName

时间:2014-01-05 13:27:12

标签: javascript getelementbyid typography getelementsbytagname getelementsbyclassname

我使用来自RobGthis answer的代码,通过id将文本放入动态宽度容器中。但理想情况下,我想同时在几个元素上使用它。我怎样才能重写此内容以使用getElementsByClassNamegetElementsByTagName

<script>

function resize(el, factor) {

  // Get element width
  var width = el.offsetWidth;

  // set default for factor
  if (typeof factor == 'undefined') {
    factor = 5;
  }

  // Set fontsize to new size
  el.style.fontSize = (width / factor | 0) + 'px';
}

window.onload = function() {
  function doResize() {resize(document.getElementById('fit'), 6);}
  window.onresize = doResize;
  doResize();
}

</script>

<div id="fit">Some text</div>

1 个答案:

答案 0 :(得分:2)

获取元素并在迭代中调用函数

function resize(el, factor) {
  // Get element width
  var width = el.offsetWidth;

  // set default for factor
  if (typeof factor == 'undefined') {
    factor = 5;
  }

  // Set fontsize to new size
  el.style.fontSize = (width / factor | 0) + 'px';
}

window.onload = function() {
  function doResize() {
      /* get a nodelist */
      var elems = document.getElementsByClassName('myClass');

      /* iterate over nodelist */
      for (var i=elems.length; i--;) {
          resize(elems[i], 6); // call function for each element
      }
  }
  window.onresize = doResize;
  doResize();
}

最好使用querySelectorAll('.myClass')而不是getElementsByClassName。 IE8支持它,getElementsByClassName不支持。