2017-06-15 59 views
0

我想使用jQuery和HTML5 data屬性的組合來動畫特定div的background-color。我願意爲實現這一目標提供最佳方式,但我相信上述內容對我的情況最有意義。使用jQuery和HTML5數據屬性的動畫背景顏色

我想在使用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> 

回答

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

這裏,這個答案是通過CSS過渡..你也可以清晰fadeing在:

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>