贴一个现成的列子//淡出函数有两个参数,第一个是要淡出的元素对象,如果传的是string的话,会把这个 string当成一个元素id,第二个参数是可选的淡出时间,默认是500毫秒 function fadeOut(e, time) { if (typeof e === "string") e = document.getElementById(e); if (!time) time = 500; // We use Math.sqrt as a simple "easing function" to make the animation // subtly nonlinear: it fades quickly at first and then slows down some. var ease = Math.sqrt; var start = (new Date()).getTime(); // Note the animation start time animate(); // And start animating function animate() { var elapsed = (new Date()).getTime()-start; // elapsed time var fraction = elapsed/time; // As a fraction of total if (fraction < 1) { // If the animation is not yet complete var opacity = 1 - ease(fraction); // Compute element opacity e.style.opacity = String(opacity); // Set it on e setTimeout(animate, // Schedule another frame Math.min(25, time-elapsed)); } else { // Otherwise, we're done e.style.opacity = "0"; // Make e fully transparent } } }
string当成一个元素id,第二个参数是可选的淡出时间,默认是500毫秒
function fadeOut(e, time) {
if (typeof e === "string") e = document.getElementById(e);
if (!time) time = 500; // We use Math.sqrt as a simple "easing function" to make the animation
// subtly nonlinear: it fades quickly at first and then slows down some.
var ease = Math.sqrt; var start = (new Date()).getTime(); // Note the animation start time
animate(); // And start animating function animate() {
var elapsed = (new Date()).getTime()-start; // elapsed time
var fraction = elapsed/time; // As a fraction of total
if (fraction < 1) { // If the animation is not yet complete
var opacity = 1 - ease(fraction); // Compute element opacity
e.style.opacity = String(opacity); // Set it on e
setTimeout(animate, // Schedule another frame
Math.min(25, time-elapsed));
}
else { // Otherwise, we're done
e.style.opacity = "0"; // Make e fully transparent
}
}
}