如何使用JavaScript和CSS淡入和淡出 [英] How to do fade-in and fade-out with JavaScript and CSS
本文介绍了如何使用JavaScript和CSS淡入和淡出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想让HTML div标记淡入淡出。
I want to make an HTML div tag fade in and fade out.
我有一些代码淡出,但是当我淡入时,div的不透明度保持在0.1,不增加。
I have some code that fades out, but when I fade in, the opacity of the div stays at 0.1 and doesn't increase.
<!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>
我做错了什么是什么是淡入和淡出元素的最佳方法? / p>
What am I doing wrong and what is the best way to fade in and fade out an element?
推荐答案
好,我已经实现了
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;
因为opacity值存储为字符串,而不是float。我仍然不确定为什么添加起作用。
Because opacity value is stored as string, not as float. I'm still not sure though why the addition has worked.
这篇关于如何使用JavaScript和CSS淡入和淡出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文