更改段落元素的颜色时,CSS悬停停止工作。
我做了一个演示来解释:https://jsfiddle.net/woan6b64/
更改<p>'s
颜色后,悬停选择器停止工作。
我的问题是:
JSFiddle代码:
var shift = 0;
function change() {
if (shift === 0) {
document.getElementById("box").style.backgroundColor = "black";
document.getElementById("text").style.color = "white";
document.getElementById("text").innerHTML = 'Good! Now click the box again.';
shift = 1;
} else {
document.getElementById("box").style.backgroundColor = "white";
document.getElementById("text").style.color = "black";
document.getElementById("text").innerHTML = 'Hover effect is now broken :(';
}
}
#box {
height: 100px;
width: 200px;
background-color: white;
}
p:hover {
color: green;
}
<div id='box' onclick='change()'>
<p id='text'>
Click me for this box to change color. (Notice how I turn green when hovered)
</p>
</div>
答案 0 :(得分:4)
停止它!如果没有必要,请不要使用!important
...您的问题是您将颜色设置为黑色。
document.getElementById("text").style.color = "";
这将使颜色继承正确的风格。
然而,这也是正确的解决方案。您应该在框中添加类,然后执行:
#box {
height: 100px;
width: 200px;
background-color: white;
}
p:hover {
color: green;
}
#box.altered {
color: white;
background-color: black;
}
.altered p:hover {
color: red;
}
&#13;
<div id="box" onclick="this.classList.toggle('altered')">
<p id='text'>
Click me for this box to change color. (Notice how I turn green when hovered)
</p>
</div>
&#13;
答案 1 :(得分:1)
添加新课程
// document.getElementById("box").style.backgroundColor = "black";
// document.getElementById("text").style.color = "white";
document.getElementById("text").classList.add("purple");
.purple {
color: purple;
}
答案 2 :(得分:0)
答案 3 :(得分:0)
如果您想使用纯JS进行操作,则需要监听onmouseover
事件和onmouseout
事件,检查我创建的代码
var textElement = document.getElementById("text");
var defaultColor = textElement.style.color;
textElement.onmouseover = function(event) {
var currentElement = event.target;
currentElement.style.color = "red";
}
textElement.onmouseout = function(event) {
var currentElement = event.target;
currentElement.style.color = defaultColor;
}
&#13;
<div id="parent">
<p id="text">
I am a text that change its text color :D
</p>
</div>
&#13;
答案 4 :(得分:-1)
设置颜色后,将覆盖悬停。使用!important来强迫它:
p:hover{
color: green !important;
}