如何重构适用于多个 div 的函数?

How to refactor my function that it works for more than one div?

我希望我的 div 在宽度超过屏幕的 20% 时移动。有谁知道如何重构 ma 函数 "isElementOverflowing()" 使其适用于多个 div(例如 3)?我使用 "getElementById" 和 "querySelectorAll" 来获取 div,但它对我的功能不起作用。

感谢您的帮助:)

<!DOCTYPE html>
<html>
<head></head>
<body>

<div id="s1" style="width:20%; font-size:2000%" class="class">something1</div>
<div id="s2" style="width:20%; font-size:2000%" class="class">something2</div>
<div id="s3" style="width:20%; font-size:2000%" class="class">something3</div>

<script type="text/javascript">

function isElementOverflowing(element) {
var overflowX = element.offsetWidth < element.scrollWidth,
overflowY = element.offsetHeight < element.scrollHeight;

return (overflowX || overflowY);
}

function wrapContentsInMarquee(element) {
var marquee = document.createElement('marquee'),
contents = element.innerText;

marquee.innerText = contents;
marquee.behavior = "alternate";
element.innerHTML = '';
element.appendChild(marquee);
}

var element = document.getElementsByClassName("class");

if (isElementOverflowing(element)) {
wrapContentsInMarquee(element);
}
</script>
</body>
</html>

我猜你可以遍历每一个:

function isElementOverflowing(element) {
  var overflowX = element.offsetWidth < element.scrollWidth,
    overflowY = element.offsetHeight < element.scrollHeight;

  return (overflowX || overflowY);
}

function wrapContentsInMarquee(element) {
  var marquee = document.createElement('marquee'),
    contents = element.innerText;

  marquee.innerText = contents;
  marquee.behavior = "alternate";
  element.innerHTML = '';
  element.appendChild(marquee);
}

var elements = document.getElementsByClassName("class");

for (var i = 0; i < elements.length; i++) {
  if (isElementOverflowing(elements[i])) {
    wrapContentsInMarquee(elements[i]);
  }
}
<div id="s1" style="width:20%; font-size:2000%" class="class">something1</div>
<div id="s2" style="width:20%; font-size:2000%" class="class">something2</div>
<div id="s3" style="width:20%; font-size:2000%" class="class">something3</div>

getElementsByClassName returns 具有所有给定 class 名称的所有子元素的类数组对象。更多信息 here.
所以在你的函数 isElementOverflowing 中你得到一个 dom 元素,而不是它们的数组。然后,你只需要迭代那些元素。

elements.forEach(function(element) {
  if (isElementOverflowing(element)) {
    wrapContentsInMarquee(element);
  }
});