[英]javascript getElementsByClassName(“foo”||“bar”)
基本上我想要一段JavaScript代碼到瀏覽器窗口的高度與上述兩個類中添加任何元素fullscreen
或fullheight
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);
這個(上面的)效果很好,我只是想知道是否有任何方法可以像jQuery equiv那樣將其壓縮為一個for(){...}
。
function fullsizes(){
$(".fullheight,.fullscreen").each(function(){
$(this).height($(window).height())
})
}
您可以使用document.querySelectorAll
返回與指定選擇器組匹配的文檔中的元素列表(使用文檔節點的深度優先順序遍歷)。 返回的對象是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";
}
}
如果您真的必須使用javascript而不是編寫一些CSS
style.css:
.fullscreen, .fullheight {
height: 100vh;
}
您可以像Satpal所說的那樣使用document.querySelectorAll。
您可以使用querySelector()
或querySelectorAll()
來做到這一點:
querySelector
返回節點的子樹中的第一個匹配Element節點。 如果找不到匹配的節點,則返回null。
querySelectorAll
返回一個NodeList,其中包含該節點的子樹中所有匹配的Element節點;如果找不到匹配項,則返回一個空的NodeList。
您可能還會發現以下網站很有用; 它包含一些示例,這些示例說明了如何不使用jQuery就可以執行類似jQuery的操作:http: //youmightnotneedjquery.com/
您可以使用concat
方法合並數組
var c = a.concat(b)
然后,您可以遍歷c
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.