CSS 样式操作:Javascript 不起作用

CSS Style manipulation : Javascript not Working

本文关键字:Javascript 不起作用 操作 样式 CSS      更新时间:2023-09-26

>我正在尝试制作一个简单的按钮,该按钮在使用 JavaScript 鼠标上更改颜色,但它不起作用,请帮忙.......html:

<head lang="en">
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="Button.css" />
<script type="text/javascript" src="Button.js"></script>
<title>BUTTON</title>
</head>
<body>
<div id="Button">PRESS ME</div>
</body>

JavaScript:

var Button = document.getElementById('Button');
Button.onmouseover(function(){
this.style.backgroundColor  = 'rgba(0,255,0,0.3)';
});

.CSS:

#Button{
width: 120px;
height : 30px;
position: fixed;
top: 100px;
left:300px;
border: 1px solid black;
background-color : rgba(0,0,255,0.3);
font-size : 25px;
}

更改

 Button.onmouseover(function(){
   this.style.backgroundColor  = 'rgba(0,255,0,0.3)';
 });

   Button.onmouseover = function(){
       this.style.backgroundColor  = 'rgba(0,255,0,0.3)';
    };

完整示例:

var Button = document.getElementById('Button');
Button.onmouseover = function () {
    this.style.backgroundColor = 'rgba(0,255,0,0.3)';
};
#Button {
    width: 120px;
    height : 30px;
    position: fixed;
    top: 100px;
    left:300px;
    border: 1px solid black;
    background-color : rgba(0, 0, 255, 0.3);
    font-size : 25px;
}
<div id="Button">PRESS ME</div>

JSFiddle demo: http://jsfiddle.net/n4j53jcu/

你混淆了两种不同的钩子事件范式。 onmouseover 是一个属性,您可以通过赋值(而不是调用它(为其分配单个函数。所以你可以做:

Button.onmouseover = function(){
    this.style.backgroundColor  = 'rgba(0,255,0,0.3)';
};

var Button = document.getElementById('Button');
Button.onmouseover = function(){
  this.style.backgroundColor  = 'rgba(0,255,0,0.3)';
};
#Button{
width: 120px;
height : 30px;
position: fixed;
top: 100px;
left:300px;
border: 1px solid black;
background-color : rgba(0,0,255,0.3);
font-size : 25px;
}
<div id="Button">PRESS ME</div>

但是现代的方法是与他人很好地玩耍,而不是打击任何以前的处理程序(上面确实如此(,而只是添加到处理程序列表中:

Button.addEventListener("mouseover", function(){
    this.style.backgroundColor  = 'rgba(0,255,0,0.3)';
}, false);

var Button = document.getElementById('Button');
Button.addEventListener("mouseover", function(){
  this.style.backgroundColor  = 'rgba(0,255,0,0.3)';
}, false);
#Button{
width: 120px;
height : 30px;
position: fixed;
top: 100px;
left:300px;
border: 1px solid black;
background-color : rgba(0,0,255,0.3);
font-size : 25px;
}
<div id="Button">PRESS ME</div>

当然,IE8 及更早版本使这变得困难,但如果您需要支持它们,您可以使用其他答案中的功能。