下面是我写的代码:
window.onload = function() {
var test = document.getElementsByClassName("experiment");
for (var i = 0; i < test.length; i++) {
test[i].addEventListener("mouseover", function(event) {
console.log('its working');
event.target.style.color = "orange";
}, false);
}
};
body {
background-color: #aaa;
}
.parent-experiment {
width: 500px;
height: 500px;
background-color: yellow;
display: flex;
justify-content: space-around;
perspective: 500px;
}
.experiment {
width: 250px;
height: 250px;
margin-top: 100px;
background-color: blue;
transform: rotateY(45deg);
}
<div class="parent-experiment">
<div class="experiment"></div>
</div>
我想要的功能是当我将鼠标悬停在内部 div 元素上时,它的颜色应该变为橙色。但它根本不起作用。此外,我只想使用 javascript 完成整个功能。
最佳答案
如果我错了,请纠正我,但我认为您正在尝试更改背景颜色属性而不是颜色属性......就像这个例子......
另一方面,您可以仅使用带有 :hover 的 css 来实现此目的选择器..
window.onload=function(){
var test=document.getElementsByClassName("experiment");
for(var i=0;i<test.length;i++){
test[i].addEventListener("mouseover",function(event){
console.log('its working');
event.target.style.backgroundColor="orange";
},false);
test[i].addEventListener("mouseout",function(event){
console.log('its working');
event.target.style.backgroundColor="blue";
},false);
}
};
body{
background-color: #aaa;
}
.parent-experiment{
width: 500px;
height: 500px;
background-color: yellow;
display: flex;
justify-content: space-around;
perspective: 500px;
}
.experiment{
width: 250px;
height: 250px;
margin-top: 100px;
background-color: blue;
transform: rotateY(45deg);
}
<div class="parent-experiment">
<div class="experiment"></div>
</div>
关于Javascript:鼠标悬停功能不适用于 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49611705/