我的HTML是:
<p id="demo">This is a test</p>
<script src="change_color.js"></script>
我的JavaScript是:
function change_color() {
if (test_text.style.color = 'black') {
test_text.style.color = 'blue';
}
else {
test_text.style.color = 'yellow';
}
}
var test_text = document.getElementById("demo");
test_text.style.color = 'black'
test_text.addEventListener("mouseover", change_color, false);
test_text.addEventListener("mouseout", change_color, false);
现在,为什么此脚本仅在鼠标悬停时更改段落的颜色。而不是鼠标输出(它保持蓝色)?
此外,是否可以在javascript函数中使用CSS选择器来设置颜色,如:
function change_color() {
#demo {
color = 'yellow'
}
答案 0 :(得分:1)
您在if语句中执行了test_text.style.color = 'black'
,该语句将颜色设置为黑色而不是检查它是否
function change_color() {
if (test_text.style.color === 'black') {
test_text.style.color = 'blue';
}
else {
test_text.style.color = 'yellow';
}
}
var test_text = document.getElementById("demo");
test_text.style.color = 'black'
test_text.addEventListener("mouseover", change_color, false);
test_text.addEventListener("mouseout", change_color, false);
&#13;
<p id="demo">This is a test</p>
<script src="change_color.js"></script>
&#13;
但是,您可以使用css hover实现相同的功能:
#demo {
color: black;
}
#demo:hover {
color: blue;
}
&#13;
<p id="demo">This is a test</p>
<script src="change_color.js"></script>
&#13;