有一个div,它的背景颜色每秒都会改变为白色。有一个按钮可以改变该div的背景颜色。单击按钮时,每秒将新的背景颜色更改为白色。
下面的代码运行正确,但是当点击按钮改变背景颜色时,只有mozilla firefox改变背景颜色。 Google Chrome 采用旧颜色。它不会更改为新颜色。
CSS:
此代码用于每秒更改 div 的背景颜色。
.circle1 {
background-color: red;
animation-name: homeCycle1;
animation-duration:1s;
animation-iteration-count:infinite;
-webkit-animation-name: homeCycle1;
-webkit-animation-duration:1s;
-webkit-animation-iteration-count:infinite;
-moz-animation-name: homeCycle1;
-moz-animation-duration:1s;
-moz-animation-iteration-count:infinite;
}
@keyframes homeCycle1
{
25% {background-color:white;}
}
@-webkit-keyframes homeCycle1
{
25% {background-color:white;}
}
@-moz-keyframes homeCycle1
{
25% {background-color:white;}
}
这是我的 jQuery 代码(它通过单击按钮运行)
function colorchange(colorCode){
$('.circle1').css({"background-color":colorCode});
}
但是当我单击 Chrome 浏览器中的按钮时,不会更改 div 的背景颜色。在 mozilla firefox 中它可以正常工作。
当我删除此 CSS 时,每个浏览器的颜色都会发生变化。但仅适用于按钮单击事件。颜色并不是每秒都在变化。
删除 CSS:
-webkit-animation-name: homeCycle1;
-webkit-animation-duration:1s;
-webkit-animation-iteration-count:infinite;
-moz-animation-name: homeCycle1;
-moz-animation-duration:1s;
-moz-animation-iteration-count:infinite;
我想为 Firefox 和 google chrome 执行此操作。
最佳答案
只需克隆该元素,然后在颜色更改后用克隆替换原始元素。 Demo
function colorchange(colorCode) {
$('.circle1').css({
"background-color": colorCode
});
var elm = $('.circle1').get(0);
var newone = elm.cloneNode(true);
elm.parentNode.replaceChild(newone, elm);
}
$(".button").click(function () {
colorchange("#ccc");
});
HTML
<div class="circle1"></div>
<button class="button">change color</button>
如果您对 .replaceChild
不满意,请尝试此 Demo
function colorchange(colorCode) {
var el =$('.circle1');
el.css({
"background-color": colorCode
});
el.replaceWith(el.clone(true));
}
编辑
当您有多个元素时,您可以使用以下代码,Demo
function colorchange(colorCode) {
var el =$('.circle1');
el.css({
"background-color": colorCode
});
el.each(function(){
$(this).replaceWith($(this).clone(true));
});
}
关于javascript - 当在 chrome 中使用 -webkit- 时,使用 jquery 更改 Div 颜色不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25882578/