简体   繁体   English

如何使用JavaScript覆盖CSS3动画?

[英]How to override CSS3 animation with Javascript?

I change the background color of the table (from lightgrey to lightgreen and back) for X seconds with CSS3 animation: 我使用CSS3动画在X秒钟内将表格的背景颜色(从浅灰色更改为浅绿色,然后返回):

        @keyframes change {
        0%   {background-color: lightgreen;}
        99%   {background-color: lightgreen;}
        100% {background-color: lightgrey;}
    }

the HTML code: HTML代码:

<tr style='background-color: lightgrey; animation: change Xs linear 5s;'>

Now I need to override the CSS animation and change the background color of the table (at any moment) to red when I click on it (and come back to lightgrey when re-click stopping the animation). 现在,我需要覆盖CSS动画,并在单击它时将表格的背景颜色(随时)更改为红色(并在重新单击停止动画时恢复为浅灰色)。 I simply try to add this code but the CSS animation always overrides the Javascript onclick command: 我只是尝试添加以下代码,但CSS动画始终会覆盖Javascript onclick命令:

onclick="this.style.animationPlayState='paused'; this.style.backgroundColor='red';"

Any suggestions? 有什么建议么? Do you think it's better to do all this in Javascript? 您认为用Java脚本做所有这些更好吗?

You might want to defer that to CSS classes and selectors: 您可能希望将其推迟到CSS类和选择器:

/* Skipping the -webkit prefix needed by chrome for sake of brevity */
.animated:not(.clicked) {
  animation: change linear 5s;
}

@keyframes change {
  0%    { background-color: lightgreen; }
  99%   { background-color: lightgreen; }
  100%  { background-color: lightgrey;  }
}

.clicked {
  background-color: red;
}

Then, just add the clicked class when the row is clicked: 然后,只需在clicked该行时添加clicked类:

// Using jQuery for simplicity

$("table").on("click", "tr", function() {
  $(this).addClass("clicked");
});

Working example: http://jsbin.com/IQaRUZa/1/edit 工作示例: http : //jsbin.com/IQaRUZa/1/edit

The solution adopted (solved with "!important" CSS3 element): 采用的解决方案(通过“!important” CSS3元素解决):

HTML code: HTML代码:

   <tr id="1" style='background-color: lightgrey; animation: change_visite 3s linear 3s;' onclick="change(document.getElementById('1'));">

CSS code: CSS代码:

@keyframes change_visite {
0%   {background-color: lightgreen;}
99%   {background-color: lightgreen;}
100% {background-color: lightgrey;}
}

.evidenziato {
background-color: coral !important;
}

JS code: JS代码:

function change(classe){
  if(classe.className === "evidenziato"){
    classe.className='';
  } else {
    classe.className='evidenziato';
  }
}

Working example here: http://jsbin.com/ENAqocUb/1/edit?html,css,js,output 这里的工作示例: http : //jsbin.com/ENAqocUb/1/edit?html,css,js,output

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

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