use*_*467 15 html javascript css
我有以下功能,当触发时会使DIV变为半透明.
function changeOpacity(el) {
var elem = document.getElementById(el);
elem.style.transition = "opacity 0.5s linear 0s";
elem.style.opacity = 0.5;
}
Run Code Online (Sandbox Code Playgroud)
但是,我希望此功能可以同时应用于多个DIV.我尝试给每个DIV相同的类名,然后使用getElementsByClassName但无法弄清楚如何实现它.
会querySelectorAll更合适,如果让我将如何实现呢?
Ath*_*ace 24
我会用querySelectorAll选择它们并循环它们.
function changeOpacity(className) {
var elems = document.querySelectorAll(className);
var index = 0, length = elems.length;
for ( ; index < length; index++) {
elems[index].style.transition = "opacity 0.5s linear 0s";
elems[index].style.opacity = 0.5;
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:正如上面的评论所说,如果这些值不是动态的并且使用以下内容,那么最好将这些值放在一个类中:
elems[index].classList.add('someclass');
Run Code Online (Sandbox Code Playgroud)
可以使用的另一种方法是使用forEach()ES6 +
function changeOpacity(className) {
document.querySelectorAll(className).forEach(el => {
el.style.transition = "opacity 0.5s linear 0s";
el.style.opacity = 0.5;
});
}
Run Code Online (Sandbox Code Playgroud)
当只需要更新一个样式属性时,我特别喜欢这种语法。例如,如果只需要更改不透明度而不是更改过渡,则可以使用单行:
function setOpacity(className) {
document.querySelectorAll(className).forEach(el => el.style.opacity = 0.5);
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用单独的方法来设置过渡:
function setTransition(className) {
document.querySelectorAll(className).forEach(
el => el.style.transition = "opacity 0.5s linear 0s";
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22213 次 |
| 最近记录: |