我在JS学习动画。我能够使用delta移动对象但在制作div的背景颜色过渡时卡住了。问题似乎是在JavaScript中,但无法弄清楚。 我希望在鼠标悬停时盒子的颜色从红色变为白色。
//var from = [0, 0, 0], to = [255, 0 ,0];
var elem = document.getElementById("animate");
var duration = 500;
function del1(progress) {
return progress;
}
function step(delt1) {
/*elem.style.backgroundColor = 'rgb(' +
parseInt(from[0] + delta * (to[0] - from[0])) + ',' +
parseInt(from[1] + delta * (to[1] - from[1])) + ',' +
parseInt(from[2] + delta * (to[2] - from[2])) + ')' ;*/
var from = [255,0,0], to = [255,255,255];
elem.style.backgroundColor = 'rgb(' +
Math.max(Math.min(parseInt((delt1 * (to[0]-from[0])) + from[0], 10), 255), 0) + ',' +
Math.max(Math.min(parseInt((delt1 * (to[1]-from[1])) + from[1], 10), 255), 0) + ',' +
Math.max(Math.min(parseInt((delt1 * (to[2]-from[2])) + from[2], 10), 255), 0) + ')';
}
funtion trans() {
var start = new Date();
var id = setInterval(change,1);
function change() {
var timePassed = new Date() - start;
var progress = timePassed / duration;
if(progress > 1) progress = 1;
var delta = del1(progress);
step(delta);
if(progress == 1) clearInterval(id);
}
}
#animate {
margin: auto;
background-color: red;
width: 250px;
height: 125px;
border: 1px solid black;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles/style.css">
</head>
<body>
<div id="animate" onmouseover="trans()">
</div>
<script src="scripts/script.js"></script>
</body>
</html>
答案 0 :(得分:1)
可能是一个简单的拼写错误,你拼写function
错误
function trans()
答案 1 :(得分:0)
不确定这只是一个练习,但更简单的方法是使用CSS!
var elem = document.getElementById("animate");
var duration = 500;
function del1(progress) {
return progress;
}
function step(delt1) {
/*elem.style.backgroundColor = 'rgb(' +
parseInt(from[0] + delta * (to[0] - from[0])) + ',' +
parseInt(from[1] + delta * (to[1] - from[1])) + ',' +
parseInt(from[2] + delta * (to[2] - from[2])) + ')' ;*/
var from = [255, 0, 0],
to = [255, 255, 255];
elem.style.backgroundColor = 'rgb(' +
Math.max(Math.min(parseInt((delt1 * (to[0] - from[0])) + from[0], 10), 255), 0) + ',' +
Math.max(Math.min(parseInt((delt1 * (to[1] - from[1])) + from[1], 10), 255), 0) + ',' +
Math.max(Math.min(parseInt((delt1 * (to[2] - from[2])) + from[2], 10), 255), 0) + ')';
}
#animate {
margin: auto;
background-color: red;
width: 250px;
height: 125px;
border: 1px solid black;
-webkit-transition: background-color 1s;
-moz-transition: background-color 1s;
-o-transition: background-color 1s;
transition: background-color 1s;
}
#animate:hover {
background-color: white;
}
<body>
<div id="animate">
</div>
<script src="scripts/script.js"></script>
</body>