简体   繁体   English

在按钮单击块上调用JS函数CSS:悬停

[英]Calling JS Function on Button Click Blocks CSS :hover

I implement a CSS hover method on all of my buttons. 我在所有按钮上实现了CSS悬停方法。 It looks like this: 看起来像这样:

.button:hover { background-color: #36a39c; }

This method works perfectly fine until I click on one of my buttons. 在我单击其中一个按钮之前,此方法可以正常工作。 When the button is clicked, a JS function is called using this code: 单击按钮后,将使用以下代码调用JS函数:

   <div id= "one"><button class="button" id = "b1" value="0" onclick="checker(this.id)"></button></div>

This is the JS Script: 这是JS脚本:

var checker = function(id)
{
   var xyz = id; 
   var value = document.getElementById(xyz).value

   if (answerjson[value].is_right_choice==1)
   {
      for (var i = 1; i <=4; i++) {
          document.getElementById("b"+i).style.background='#722F37';
      }
      document.getElementById(xyz).style.background='green';
      setTimeout(function(){ alert("Correct!"); }, 100);
   }
   else {
        for (var i = 1; i <=4; i++) {
          document.getElementById("b"+i).style.background='#722F37';

        }
        document.getElementById(xyz).style.background='red';
        setTimeout(function(){ alert("Sorry, Try Again"); }, 100);

   }

}

After that script is called, my buttons no longer change color on hover. 调用该脚本后,悬停时我的按钮不再更改颜色。 Any ideas why? 有什么想法吗?

You're setting the inline style="" attribute in your JS code. 您正在JS代码中设置inline style=""属性。

Properties set in inline styles always override CSS selectors (except with !important ), so your CSS no longer does anything. 内联样式设置的属性始终会覆盖CSS选择器( !important除外),因此CSS不再执行任何操作。

You should add a CSS class instead of setting an inline style. 您应该添加CSS类,而不是设置内联样式。

This happens because when you add background color using javascript it is added as inline styling and it overrides the css class selector because inline styling always takes more preference. 发生这种情况的原因是,当您使用javascript添加背景色时,它会作为内联样式添加,并且会覆盖css类选择器,因为内联样式始终需要更多的首选项。 You need to make a class with that color and add/remove that using javascript. 您需要使用该颜色制作一个类,然后使用javascript添加/删除该颜色。 eg make a class 例如上课

.green{
   background-color: green;
}

and then add it using javascript like this: 然后使用javascript将其添加如下:

document.getElementById(xyz).className += " green";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM