javascript如何使用带有命名空间的脚本在div元素上使用hover元素?

javascript如何使用带有命名空间的脚本在div元素上使用hover元素?,javascript,namespaces,hover,Javascript,Namespaces,Hover,在这段代码中,我在将鼠标悬停在div上时更改了div的颜色。如何在不使用样式的情况下实现这一点,而是将其放在具有名称空间的脚本中 <html> <head> <title></title> <style type="text/css"> .link-container { border: 1px solid; width: 50%; height: 20px; } .link-container a {

在这段代码中,我在将鼠标悬停在div上时更改了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>

.链接容器{
边框:1px实心;
宽度:50%;
高度:20px;
}
.连接容器a{
显示:块;
背景:绿色;
身高:100%;
文本对齐:居中;
}
.链接容器a:悬停{
背景:红色;
}
悬停以更改颜色

您可以在元素的事件上方使用
鼠标

[].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'
    });
})

添加eventListeners,然后在命名空间中启动函数(比如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);