javascript getElementsByClassName("foo"||"bar")

javascript getElementsByClassName("foo"||"bar")

基本上我想要一个 javascript 的片段来将浏览器的高度 window 添加到具有 类 的 either 的任何元素fullscreenfullheight

function fullsize(){
    var a = document.getElementsByClassName("fullscreen"),
        b = document.getElementsByClassName("fullheight");
    for (var i=0; i<a.length; i++){
        a[i].style.height = window.innerHeight + "px";
    }
    for (var j=0; j<b.length; j++){
        b[j].style.height = window.innerHeight + "px";
    }
}
window.addEventListener("load", fullsize),
window.addEventListener("resize", fullsize);

这个(上面的)效果很好,我只是想知道是否有任何方法可以将它压缩成一个 for(){...},就像 jQuery 等价物。

function fullsizes(){
    $(".fullheight,.fullscreen").each(function(){
      $(this).height($(window).height())
    })
}

您可以使用document.querySelectorAll

Returns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes) that match the specified group of selectors. The object returned is a NodeList.

代码示例

document.querySelectorAll(".fullscreen, .fullheight"); 

更改代码

function fullsize(){
    var a = document.querySelectorAll(".fullscreen, .fullheight"); 
    for (var i=0; i<a.length; i++){
        a[i].style.height = window.innerHeight + "px";
    }
}

您可以使用 concat 方法合并数组

var c = a.concat(b)

然后您可以迭代 c

如果真的要用javascript而不是写一些css

style.css:

.fullscreen, .fullheight {
    height: 100vh;
}

你可以像 Satpal 说的那样使用 document.querySelectorAll。

您可以使用 querySelector() or querySelectorAll() 来执行此操作:

querySelector

Returns the first matching Element node within the node's subtree. If no matching node is found, null is returned.

querySelectorAll

Returns a NodeList containing all matching Element nodes within the node's subtree, or an empty NodeList if no matches are found.

您可能还会发现以下网站有用;它包含如何在不使用 jQuery 的情况下做类似 jQuery 的事情的示例:http://youmightnotneedjquery.com/