在任何人聲明這一點之前,是的,我知道你可以在CSS中過渡事物。但是,我想知道如何在JavaScript中轉換背景顏色。我正在處理這個函數,它將ex1的id背景變爲綠色,但setInterval函數只運行一次,這很奇怪。如何在javascript中設置顏色轉換?
CSS:
<style type="text/css">
div#ex1{color:white; background:black; width:300px; padding:0px 10px 10px; margin-bottom:10px;}
div#ex1:hover{cursor:pointer;}
div#ex1 h2{border-bottom:double 3px white; text-align:center; padding: 5px 0; margin: auto -10px;}
div#ex1 p{text-indent:5px;}
</style>
HTML
<div id="ex1">
<h2>Transition Color</h2>
<h4>Text:</h4>
<p>Church-key seitan listicle locavore, mixtape biodiesel readymade crucifix health goth flexitarian direct trade mlkshk iPhone. Banjo tote bag readymade +1 skateboard deep v. Mixtape cred readymade gentrify. Banh mi keytar butcher, skateboard knausgaard </p>
</div>
使用Javascript:
document.getElementById('ex1').addEventListener('mouseover', function(e){
var tar = this;
var counter;
var backG = window.getComputedStyle(tar,null).getPropertyValue('background-color');
console.log(backG);
var re,gr,bl;
gr = 0;
bl = 0;
function chColor(tar)
{ gr =+31;
bl=+10;
if (gr <153 && bl <51)
{ console.log('This is running');
tar.style.backgroundColor = 'rgb(0,'+gr+','+bl+')';
}
else
{
clearInterval(counter);
console.log(backG);
console.log('The change has ended');
}
}
counter = setInterval(chColor(tar),100);
}, false);
你能更具體地說明你的問題是什麼嗎?你的問題是你無法弄清楚如何轉換顏色?或者你不能讓它運行多次?或者是其他東西? –