[英]Show 4 images step by step with effect in javascript
<!DOCTYPE html>
<html>
<head>
<style>
#steps img{
-webkit-transition: background-image 1.0s linear 0s;
transition: background-image 1.0s linear 0s;
float: left;
display: none;
height: 50px;
width: 50px;
}
</style>
<script>
var i = 0;
var elem;
function nextStep(){
i++;
var img = document.createElement("img");
img.src = "image"+i+".png"
img.width = "50px";
img.height = "50px";
img.id = "step" + i;
document.getElementById("steps").appendChild(img);
elem = document.getElementById(img.id);
elem.style.display = "inline-block";
elem.style.opacity = "0";
setTimeout(slide(),5000);
}
function slide(){
elem.style.opacity = "1";
if(i > 3){
clearTimeout(slide());
clearTimeout(nextStep());
}
setTimeout(nextStep(),5000);
}
</script>
</head>
<body>
<h1>Steps</h1>
<div id="steps">
<script>
nextStep();
</script>
</div>
<p id="text"></p>
</body>
</html>
我有4张图像,我想用css3效果逐步创建和显示它们,它首先执行nextStep()函数,该函数创建img子元素以div并更改显示和不透明度。 调用slide()之后,将不透明度设置为1,然后再次调用nextStep()。 当我> 3时,我们停止显示。 当我测试它时,它立即显示4张图像,没有任何影响
编辑:
<!DOCTYPE html>
<html>
<head>
<style>
#steps img{
/*
-webkit-transition: background-image 1.0s linear 0s;
transition: background-image 1.0s linear 0s;
*/
float: left;
display: none;
height: 50px;
width: 50px;
}
</style>
<script>
var i = 0;
var elem;
//var slide;
//var nextStep;
function nextStep(){
i++;
var img = document.createElement("img");
img.src = "image"+i+".png"
img.width = "50px";
img.height = "50px";
img.id = "step" + i;
document.getElementById("steps").appendChild(img);
elem = document.getElementById(img.id);
elem.style.display = "inline-block";
//elem.style.opacity = "0";
setTimeout(slide(),2000);
}
function slide(){
//elem.style.opacity = "1";
if(i < 3){
//clearTimeout(slide());
//clearTimeout(nextStep());
setTimeout(nextStep(),2000);
}
}
</script>
</head>
<body>
<h1>Steps</h1>
<div id="steps">
<script>
document.onload = function (){
nextStep();
};
</script>
</div>
<p id="text"></p>
</body>
</html>
在对其进行任何操作之前,您应始终等待DOM完全加载。 加载文档后,使用document.onload执行脚本:
<script>
document.onload = function (){
nextSteps()
};
</script>
编辑:您的代码还有更多问题。 这里不需要clearTimeout
函数。 另外,您使用的也不正确。 引用来自w3schools的文档:
clearTimeout()方法清除使用setTimeout()方法设置的计时器。
setTimeout()返回的ID值用作clearTimeout()方法的参数。
注意:为了能够使用clearTimeout()方法,在创建超时方法时必须使用全局变量:
myVar = setTimeout("javascript function",milliseconds);
然后,如果尚未执行该函数,则可以通过调用clearTimeout()方法来停止执行。
您的幻灯片功能应如下所示:
function slide(){
elem.style.opacity = "1";
if(i < 3){
setTimeout(nextStep,5000);
}
}
编辑2:
setTimeout
需要对函数的引用 ,例如, 不带括号的函数名称:
setTimeout(nextStep,5000);
nextStep
是对函数的引用
nextStep()
是函数执行后返回的结果(在这种情况下未定义)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.