[英]Animate background-color using jquery and HTML5 data attribute
我正在尝试使用jQuery和HTML5 data
属性的组合来动画特定div的background-color
。 我对实现这一目标的最佳方法持开放态度,但是我认为以上情况对我的情况最有意义。
我想在使用Wordpress Advanced Custom Fields插件设置的一系列颜色之间淡入淡出,因此要使用data
属性,因此我可以在DOM中动态设置这些颜色。
下面是div
的标记,包括颜色,但是我不知道如何实现的是jQuery在所有颜色之间进行动画处理,理想情况下是随机的。
有人可以协助吗? 谢谢。
<div id="content" data-colors="<?php if( have_rows('dot_colours', 'option') ): ?><?php while( have_rows('dot_colours', 'option') ): the_row(); ?><?php the_sub_field('colour'); ?>,<?php endwhile; ?><?php endif; ?>
">
Content here.
</div>
这样的事情会起作用:
HTML (假设PHP返回data-colors
值的数组)
<div id="myDiv" data-colors='["#b3e45f", "red", "yellow", "green", "blue"]'></div>
JavaScript的
const el = $('#myDiv');
const colors = el.data('colors');
let i = 0;
el.css("background-color", colors[i]);
function changeColor() {
i++;
i = i % colors.length;
el.animate({backgroundColor: colors[i]},1000);
setTimeout(changeColor,2500);
}
changeColor();
这是一个Codepen来演示: https ://codepen.io/MarkRabey/pen/MobeLo
编辑 :忘了提一下,彩色动画是jQuery UI而非jQuery的一部分。 没有jQuery UI,您可以改用CSS过渡。
添加到您的CSS:
#myDiv {
transition: background-color 1s;
}
将changeColor()
函数更改为:
function changeColor() {
i++;
i = i % colors.length;
el.css('background-color', colors[i]);
setTimeout(changeColor,2500);
}
在这里,这个答案是通过CSS转换..您也可以使用以下方法清除淡入:
clearInterval( window.it );
var arr = $('.ch').first().attr('data-colors'); // "red, green, blue, purple, gray" arr = arr.split(','); // ["red", " green", " blue", " purple", " gray"] // set attrib for first time $('.ch').first().attr('len', 0 ); function changeColor(){ var len = arr.length; var atm = $('.ch').first().attr('len'); $('.ch').first().css( 'background-color', arr[ atm ] ); if( atm == len ) $('.ch').first().attr('len', 0 ); if( atm != len ) $('.ch').first().attr('len', parseInt(atm) + 1 ); } window.it = setInterval( changeColor, 2000 );
.ch{ background-color: red; -webkit-transition:background 2s; -moz-transition:background 2s; -o-transition:background 2s; transition:background 2s; width: 100vw; height: 100vh; } body{ margin: 0; padding: 0; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="ch" data-colors="red, green, blue, purple, gray"> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.