gpt4 book ai didi

javascript - 当在 chrome 中使用 -webkit- 时,使用 jquery 的 Div 颜色更改不起作用

转载 作者:行者123 更新时间:2023-11-29 21:57:12 25 4
gpt4 key购买 nike

有一个div。它的背景颜色每秒都变成白色。有一个按钮可以改变那个div的背景颜色。单击按钮时,每秒将新的背景颜色更改为白色。

以下代码运行正确。但是当单击按钮更改背景颜色时,只有 mozilla firefox 更改背景颜色。谷歌浏览器采用旧颜色。它不会更改为新颜色。

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com