如何在javascript中设置颜色过渡?

时间:2016-04-05 18:03:09

标签: javascript html css

在有人陈述之前,是的,我知道你可以用css过渡。但是,我想知道如何在javascript中转换背景颜色。我正在处理这个函数,它将div的背景改为ex1的绿色,但setInterval函数只运行一次,这很奇怪。

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

2 个答案:

答案 0 :(得分:1)

setInterval将对函数的引用作为它将在每个时间间隔调用的第一个参数。你有它的方式,你传递函数的返回值。试试这个:

setInterval(function () {
     chColor(tar);
},100);

答案 1 :(得分:1)

这两行代码需要更正,因为您需要使用+=而不是=+。否则,值将永远不会增加。

gr += 31;
bl +=10;

然后看看mcgraphix的帖子。您还必须这样做,以便在文本被鼠标悬停时让动画更改颜色。 (我也要提到这一点,但他打败了我。:)