2017-02-27 80 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>