我正在尝试使用javascript为show / div制作动画。代码工作正常,但我希望它以500速开启和关闭。
我的代码是:
<a id="show-map" href="javascript:toggle();">Show Map</a>
<div id="top-map" style="display: none">
<h2>Hello</h2>
</div>
<script language="javascript">
function toggle() {
var ele = document.getElementById("top-map"),
text = document.getElementById("show-map");
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "Show Map";
} else {
ele.style.display = "block";
text.innerHTML = "Hide Map";
}
}
</script>
答案 0 :(得分:0)
您需要使用setInterval或requestAnimationFrame等时间函数 这是setInterval
的一个例子//to fade out
fadeout_interval = setInterval(function(el){
el.style.opacity -= 0.1;
if(el.style.opacity<=0) clearInterval(fadeout_interval);
}, 30, ele);
或者你可以用css做同样的事情
答案 1 :(得分:0)
根据keypaul here发布的示例,我已经调整了您的代码并为您缩短了示例:
<a id="show-map" href="javascript:toggle();">Show Map</a>
<div id="top-map" style="display: none">
<h2>Hello</h2>
</div>
<script language="javascript">
var ele = document.getElementById("top-map"),
text = document.getElementById("show-map");
function setTime(state) {
if (state === "out") {
for (var i = 1; i <= 100; i++) {
setTimeout("fadeOut(" + (100 - i) + ")", i * 5);
}
} else {
for (var i = 1; i <= 100; i++) {
setTimeout("fadeIn(" + (0 + i) + ")", i * 5);
}
}
}
function fadeOut(opacity) {
ele.style.opacity = opacity / 100;
if (opacity === 1) {
ele.style.display = "none";
}
}
function fadeIn(opacity) {
ele.style.opacity = opacity / 100;
if (opacity === 1) {
ele.style.display = "block";
}
}
function toggle() {
if(ele.style.display == "block") {
setTime("out");
text.innerHTML = "Show Map";
} else {
setTime("in");
text.innerHTML = "Hide Map";
}
}
</script>