我使用来自RobG的this answer的代码,通过id将文本放入动态宽度容器中。但理想情况下,我想同时在几个元素上使用它。我怎样才能重写此内容以使用getElementsByClassName
或getElementsByTagName
?
<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>
答案 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
不支持。