[英]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.