Javascript:鼠标悬停功能不适用于 div

标签 javascript html 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.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/

相关文章:

CSS3 过滤器 :opacity(X) with fallback to opacity:X, 与过滤器相同:drop-shadow() 到 box-shadow

javascript - 通过 jquery 更改 CSS 左像素

javascript - slider 在多个 div 中不起作用

javascript - 显示光标下的文本

javascript - 在打开页面时使用 JQuery 隐藏 Div 类

javascript无法获取数据索引的索引号

html - 禁用 Windows 8 IE10+ 默认 "touch-enabled"下拉列表功能

javascript - if 循环有很多参数 ( 1000 && )

javascript - 如何在多个按钮上分别切换每个按钮?

html - 如何使用固定顶部解决错误设置侧边栏