2017-02-27 87 views
-1

我想在javascript中應用動畫,我已經在外部css中聲明瞭。所有我的html,css,javascript中只有一個擴展名爲.html的文件這裏是我的代碼。如何從JavaScript調用外部CSS?

<html> 
<head> 

<style> 

@keyframes example { 

0% {background-color: red; transform:translate(0px,0px)rotate(180deg);} 
25% {background-color: green; transform:translate(0px,-150px);} 
50% {background-color: blue; transform:translate(0px,-300px);} 
75% {background-color: pink; transform:translate(0px,-455px);} 
100% {background-color: yellow; transform:translate(0px,0px);} 
} 

#1 
{ 
margin-top: 350px; 
margin-left: 1190px; 
animation-name: example; 
animation-duration: 4s; 
} 
</style> 

<script language="javascript"> 
function abc() 
    { 
    var a=document.getElementById("1"); 
    a.style.Animation-Name="example" ; // i have full doubt here css animation is not switching from here 
    } 
</head> 
<body> 
<a href="#" id="1" onclick="abc();" />onclick 
</body> 
</html> 
+0

'.style.animationName' – j08691

+0

#j08691你的意思是這個'功能ABC(){ VAR A =的document.getElementById( 「ID6」); a.style.animationname =「example」; '它不起作用 –

+0

不,'animationName'。區分大小寫。另外,如果你在webkit瀏覽器中這樣做,你可能需要'webkitAnimationName' – j08691

回答

0

嘿拉傑我看到你的文章,我只修改了幾件事情來達到這個答案。 webkit的新增功能如下:https://www.w3schools.com/css/css3_animations.asp。他們添加多個瀏覽器支持。

animate函數使用三元運算符。我修改了邊距的大小以更好地跟蹤動畫。

這個問題可能是一個更有說服力的解決方案,但我希望這可以幫助你!祝你今天愉快。

<!DOCTYPE html> 
<html> 
    <head> 
    <style> 
    .standard.animate { 
     margin-top: 100px; 
     margin-left: 200px; 
     position: relative; 
     background-color: red; 
     -webkit-animation-name: example; 
     -webkit-animation-duration: 4s; 
     animation-name: example; 
     animation-duration: 4s; 
    } 

    @-webkit-keyframes example { 
    0% {background-color: red; transform:translate(0px,0px)rotate(180deg);} 
    25% {background-color: green; transform:translate(0px,-150px);} 
    50% {background-color: blue; transform:translate(0px,-300px);} 
    75% {background-color: pink; transform:translate(0px,-455px);} 
    100% {background-color: yellow; transform:translate(0px,0px);} 
} 

@keyframes example { 
    0% {background-color: red; transform:translate(0px,0px)rotate(180deg);} 
    25% {background-color: green; transform:translate(0px,-150px);} 
    50% {background-color: blue; transform:translate(0px,-300px);} 
    75% {background-color: pink; transform:translate(0px,-455px);} 
    100% {background-color: yellow; transform:translate(0px,0px);} 
} 
    </style> 
    </head> 
<body> 
    <div class="standard">on Click</div> 
    <script> 

    const animateDiv = document.querySelector('.standard'); 

    function animate() { 
     this.classList.contains('animate') ? this.classList.remove('animate') : 
     this.classList.add('animate'); 
    } 

    animateDiv.addEventListener('click', animate); 

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