我对mouseover事件有一个问题。当我将鼠标悬停在其中一个div上时,div (主页)上的颜色会完全改变,但当我将鼠标悬停在另一个div(测试)上时,这个div也会变成相同的颜色,所以我会同时拥有两个相同颜色的div。
我想要的是,如果你转到另一个div,mouseover将从原来的div上消失。所以一次只能有一个div有mousover事件。我是JS的新手,如果有人能帮我解决这个问题,那就太棒了!
下面是我的代码:
HTML
<li class="first" id="color"><a href="index.php">Home</a></li>
<li id="color1" ><a href="index.php?content=test">test</a></li>JavaScript
var div = document.getElementById( 'color' );
div.onmouseover = function() {
this.style.backgroundColor = 'red';
}
var div = document.getElementById( 'color1' );
div.onmouseover = function() {
this.style.backgroundColor = 'red';
}发布于 2017-02-17 07:09:09
考虑一下只包含两个li元素的示例。请找到下面的答案。
var div = document.getElementById( 'color' );
div.onmouseover = function() {
this.style.backgroundColor = 'red';
}
div.onmouseleave=function() {
this.style.backgroundColor = "white";
}
var div = document.getElementById( 'color1' );
div.onmouseover = function() {
this.style.backgroundColor = 'red';
}
div.onmouseleave=function() {
this.style.backgroundColor = "white";
}发布于 2017-02-17 07:03:55
您需要一个相反的函数来关闭添加的background-color属性。
var div = document.getElementById('color');
div.onmouseover = function() {
this.style.backgroundColor = 'red';
}
div.onmouseleave = function() {
this.style.backgroundColor = 'transparent';
}
var div1 = document.getElementById('color1');
div1.onmouseover = function() {
this.style.backgroundColor = 'red';
}
div1.onmouseleave = function() {
this.style.backgroundColor = 'transparent';
}<li class="first" id="color"><a href="index.php">Home</a></li>
<li id="color1"><a href="index.php?content=test">test</a></li>
但是有更简单的方法,只要在css。中就可以了。
li:hover {
background-color: red;
}<li class="first" id="color"><a href="index.php">Home</a></li>
<li id="color1"><a href="index.php?content=test">test</a></li>
发布于 2017-02-17 07:04:02
有更好的方法来实现这一点。
在学习JavaScript的过程中,您可以看到onmouseleave事件并在此处恢复背景颜色。
var div = document.getElementById('color');
div.onmouseover = function() {
this.style.backgroundColor = 'red';
}
div.onmouseleave = function() {
this.style.backgroundColor = '';
}
var div2 = document.getElementById('color1');
div2.onmouseover = function() {
this.style.backgroundColor = 'red';
}
div2.onmouseleave = function() {
this.style.backgroundColor = '';
}<li class="first" id="color"><a href="#">Home</a></li>
<li id="color1"><a href="#">test</a></li>
https://stackoverflow.com/questions/42286320
复制相似问题