簡體   English   中英

使用css為javascript添加動畫

[英]add animation to javascript using css

我使用下面的代碼使用CSS向幻燈片添加動畫。 但動畫僅應用於第一張圖像而不應用於其他圖像。 如何僅使用css將過渡添加到其他圖像?

<html>
    <style>
        #slideshow{width:310;height:210;border-style:solid;}
        #imge{
            position:absolute;left:15;top:15;
            animation:myfirst 3s;}
        @keyframes myfirst
        {
            from {width:0;}
        to {width:300;}
        }

        @-webkit-keyframes myfirst /* Safari and Chrome */
        {
            from {width:0;}
        to {width:300;}
        }

    </style>
    <body>
        <div id="slideshow">
            <img id="imge" src="img1.jpg" height="200" width="300">
        </div>
        <script>
            var count=1;
            mf();
            function mf()
            {
                document.getElementById("imge").src="img"+count+".jpg";

                if(count<3)
                    count++;
                else
                    count=1;
                setTimeout("mf()",3000);
            }

        </script>
    </body>
</html>

使用CSS3動畫屬性animation-iteration-count

指定播放動畫的次數。 默認值為1,因此將其設為無限

試試這段代碼:

小提琴

#slideshow{width:310px;height:210px;border-style:solid;}
#imge{
position:absolute;left:15;top:15;
width:310px;height:210px;
animation:myfirst 3s;
animation-iteration-count:infinite;
-webkit-animation:myfirst 5s; /* Safari and Chrome */
-webkit-animation-iteration-count:infinite;}

@keyframes myfirst
{
from {width:0px;}
to {width:300px;}
}

@-webkit-keyframes myfirst /* Safari and Chrome */
{
from {width:0px;}
to {width:300px;}
}

JS

var count=1;
mf();
function mf()
{
document.getElementById("imge").src="img"+count+".jpg";

if(count<3)
count++;
else
count=1;
setTimeout("mf()",3000);
}

你想要的是css的animation-iteration-count屬性。 你可以在這里查看

通過設置數字,您可以確定圖像顯示特定動畫的次數。 在您的情況下,您可以將其設置為3,因為您有3張圖像。 你也可以使用count infinite循環它

<img id="imge" src="img1.jpg" height="200" width="300">

改成

<img class="imge" id="imge1" src="img1.jpg" height="200" width="300" style="display:none;"/>
<img class="imge" id="imge2" src="img2.jpg" height="200" width="300" style="display:none;"/>
<img class="imge" id="imge3" src="img3.jpg" height="200" width="300" style="display:none;"/>

所以css #imge應該是.imge

JavaScript的

function mf()
{
  for(var i=1;i<4;i++)
  {
     document.getElementById("imge"+i).style.display="none";
  }  

  document.getElementById("imge"+count).style.display="block";

 if(count<3)
  count++;
 else
  count=1;
 setTimeout("mf()",3000);

}

在進行圖像顯示時,將觸發動畫

id轉到class es:

而不是這個:

    <div id="slideshow">
        <img id="imge" src="img1.jpg" height="200" width="300">
    </div>

    #slideshow{...}
    #imge{...}

對此:

    .slideshow{...}
    .imge{...}        

原因是id唯一的 (你只能有一個),但類不是。

希望這可以幫助。 干杯

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM