首页 > 解决方案 > 如何在 addEventListner 中设置不透明度样式?

问题描述

const mainDiv = document.getElementsByClassName('home-bg-image');
const homeMainDiv = document.getElementsByClassName('home-bg');
const homeDiv = document.getElementById('home-1');




homeDiv.addEventListener('mouseenter', e => {
    mainDiv.style.opacity = '0';
    homeMainDiv.style.opacity = '1';
    console.log('Working !!!')
});

我收到此错误未捕获类型错误 :无法在 HTMLDivElement 处设置未定义的属性“不透明度”。

标签: coding-stylemouseeventaddeventlisteneropacitymouseenter

解决方案


documents.getElementsByClassName返回一个数组。

您应该使用方括号表示法访问要设置样式的元素

mainDiv[0].style.opacity = '0';
homeMainDiv[0].style.opacity = '1';

推荐阅读