如果我使用JavaScript更改BG颜色,如何使用CSS .hover?

时间:2016-07-05 23:46:13

标签: javascript html css

如果没有选择难度,我希望按钮保持灰色。选择后,按钮应变为不同的颜色。我希望.hover始终适用于按钮。这是我目前的非工作代码:

<div id="start">
<p id="startText" class="text">Find random exercise!</p>
</div>
<style>

#start{/*styling for the button and the text inside as well as .hover*/
 width: 50%;
 height: 100px;
 background-color: gray;
 position: absolute;
 top: 50%;
 left: 24%;
}
#startText{
 position: absolute;
 top: 15%;
 left: 14%;
}
#start:hover{
 background-color: yellow;
}
</style>

<ul id="difficulty"><!--Here I have a ul with the difficulties to select
<li id="easy" class="list" onclick="shadows(1)">Easy</li>
<li id="medium" class="list" onclick="shadows(2)">Medium</li>
<li id="hard" class="list" onclick="shadows(3)">Hard</li>
</ul>

单击难度后,将运行shadows()函数。这是:

var start=document.getElementById("start");
function shadows(number){
 start.style.cursor="pointer";
 start.style.backgroundColor="#ffffb3"; //I change the color of the background
 if(number==1){
  chosenDifficulty=.5;
 }
 else if(number==2){
  chosenDifficulty=1;
 }
 else{
  chosenDifficulty=1.5;
 }
}

如何更改背景颜色而不影响悬停?

2 个答案:

答案 0 :(得分:1)

#start:hover{
 background-color: yellow!important;
}

答案 1 :(得分:0)

还记得css的级联效应吗?将'#start:hover'放在'start.style.backgroundColor'之后,悬停将在触发时覆盖现有颜色。如果没有悬停,则返回原始BG颜色。