【问题标题】:javascript how do i use the hover element on a div-element using a script with namespace?javascript 如何使用带有命名空间的脚本在 div 元素上使用悬停元素?
【发布时间】:2016-12-18 15:45:27
【问题描述】:
在这段代码中,我在将鼠标悬停在 div 上时更改了它的颜色。我怎样才能在不使用样式的情况下实现这一点,而是将其放在带有命名空间的脚本中?
<html>
<head>
<title></title>
<style type="text/css">
.link-container {
border: 1px solid;
width: 50%;
height: 20px;
}
.link-container a {
display: block;
background: green;
height: 100%;
text-align: center;
}
.link-container a:hover {
background: red;
}
</style>
</head>
<body>
<div class="link-container">
<a>hover to change color</a>
</div>
</body>
</html>
【问题讨论】:
标签:
javascript
namespaces
hover
【解决方案1】:
你可以使用元素的mouseover事件。
[].forEach.call(document.getElementsByClassName('link-container'),function(e){
e.addEventListener("mouseover", function(){
this.style.background='red'
});
});
编辑:
您需要mouseout 事件来移除应用的样式。
[].forEach.call(document.getElementsByClassName('link-container'),function(e){
e.addEventListener("mouseover", function(){
this.style.background='red'
});
e.addEventListener("mouseout", function(){
this.style.background='inherit'
});
})
【解决方案2】:
添加 eventListener,然后在您的命名空间中触发函数(比如 myApp)
var myApp = {
hover: function(event){
event.target.setAttribute("style", "background-color:red;")
},
out: function(event){
event.target.setAttribute("style", "background-color:green;")
}
}
var item = document.getElementById("btn");
item.addEventListener("mouseover", myApp.hover, false);
item.addEventListener("mouseout", myApp.out, false);
Plunker here