以下是我写的代码:
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完成整个功能。
答案 0 :(得分:2)
纠正我如果我错了,但我认为您正在尝试更改背景颜色属性而不是颜色属性..就像示例...
另一方面,您可以仅使用带有: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);
}
};
&#13;
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);
}
&#13;
<div class="parent-experiment">
<div class="experiment"></div>
</div>
&#13;