我想让HTML div标签淡入淡出。
我有一些淡出的代码,但是当我淡入时,div的不透明度保持在0.1且不会增加。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en"> <head> <title>Fade to Black</title> <script type="text/javascript"> //<![CDATA[ function slidePanel(elementToSlide, slideSource) { var element = document.getElementById(elementToSlide); if(element.up == null || element.up == false) { setTimeout("fadeOut(\"" + elementToSlide + "\")", 100); element.up = true; slideSource.innerHTML = "Bring it down"; } else { setTimeout("fadeIn(\"" + elementToSlide + "\")", 100); element.up = false; slideSource.innerHTML = "Take it up"; } } function fadeIn(elementToFade) { var element = document.getElementById(elementToFade); element.style.opacity += 0.1; if(element.style.opacity > 1.0) { element.style.opacity = 1.0; } else { setTimeout("fadeIn(\"" + elementToFade + "\")", 100); } } function fadeOut(elementToFade) { var element = document.getElementById(elementToFade); element.style.opacity -= 0.1; if(element.style.opacity < 0.0) { element.style.opacity = 0.0; } else { setTimeout("fadeOut(\"" + elementToFade + "\")", 100); } } //]]> </script> </head> <body> <div> <div id="slideSource" style="width:150px; height:20px; text-align:center; background:green" onclick="slidePanel('panel', this)"> Take It up </div> <div id="panel" style="width:150px; height:130px; text-align:center; background:red; opacity:1.0;"> Contents </div> </div> </body> </html>
我在做什么错,淡入淡出元素的最佳方法是什么?
好,我已经解决了
element.style.opacity = parseFloat(element.style.opacity) + 0.1;
应该代替
element.style.opacity += 0.1;
与相同
element.style.opacity = parseFloat(element.style.opacity) - 0.1;
代替
element.style.opacity -= 0.1;
因为不透明度值存储为字符串,而不是浮点数。我仍然不确定为什么添加成功了。