querySelectorAll和具有相同类的多个元素 [英] querySelectorAll and multiple elements with the same class
问题描述
我当前正在尝试此演示来适应单击页面时的过渡具有相同类的链接应用于它们.
I am currently trying to adapt this demo for page transitions when you click on the links with the same class applied to them.
我不确定在使用querySelectorAll
之后如何对具有相同类的所有元素采用以下代码.您认为应该进行哪些调整才能使其与querySelectorAll
和同一个类的多个元素一起使用?
I am not sure how to adapt the following piece of code for all the elements that has the same class following the use of querySelectorAll
. What do you think should be tweaked to make it work with querySelectorAll
and multiple elements with the same class?
(function() {
const elmHamburger = document.querySelector('.link-with-overlay');
const elmOverlay = document.querySelector('.shape-overlays');
const overlay = new ShapeOverlays(elmOverlay);
elmHamburger.addEventListener('click', () => {
if (overlay.isAnimating) {
return false;
}
overlay.toggle();
if (overlay.isOpened === true) {
elmHamburger.classList.add('is-opened-navi');
} else {
elmHamburger.classList.remove('is-opened-navi');
}
谢谢!
推荐答案
要允许所有链接具有onclick事件,您需要遍历querySelectorAll
方法返回的NodeList
.
To allow all the links to have an onclick event you'll need to iterate over the NodeList
that the querySelectorAll
method returns.
注意:您无法在IE11中执行NodeList.forEach
,因此您需要在迭代之前进行polyfill或将其转换为真正的JS数组.
NOTE: You cannot do NodeList.forEach
in IE11 so you'd need to polyfill or convert it to a true JS array before iterating.
(function() {
const elmHamburgers = document.querySelectorAll('.link-with-overlay');
const elmOverlay = document.querySelector('.shape-overlays');
const overlay = new ShapeOverlays(elmOverlay);
const onHamburgerClick = function() {
if (overlay.isAnimating) {
return false;
}
overlay.toggle();
if (overlay.isOpened === true) {
this.classList.add('is-opened-navi');
} else {
this.classList.remove('is-opened-navi');
}
};
// Iterates over all of the elements matched with class .link-with-overlay and
// adds an onclick event listener
elmHamburgers.forEach(elem => elem.addEventListener('click', onHamburgerClick));
})();
您也可以替换条件:if (overlay.isOpened === true) {...
用this.classList
You could also replace the conditional: if (overlay.isOpened === true) {...
with a one liner using this.classList
this.classList.toggle('is-opened-navi', overlay.isOpened)
这篇关于querySelectorAll和具有相同类的多个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!