使用jquery和HTML5数据属性为背景颜色设置动画

时间:2017-06-15 13:32:34

标签: javascript jquery css html5

我正在尝试使用jQuery和HTML5 background-color属性的组合来动画特定div的data。我对实现这一目标的最佳方式持开放态度,但我相信上述内容对我的情况最有意义。

我希望在使用Wordpress高级自定义字段插件设置的颜色数组之间淡入淡出,因此使用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>

2 个答案:

答案 0 :(得分:0)

这样的事情会起作用:

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);
}

答案 1 :(得分:0)

这里,这个答案是通过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">&nbsp;</div>