java脚本函数只能工作一次

时间:2015-09-01 02:42:20

标签: javascript function css-transforms

这是用于旋转p元素的函数:

<script>
function ani() {

  var z = document.getElementById("rotate");
  z.style.webkitTransition = "1.2s";
  z.style.transition = "1.2s" ;
  z.style.transform = "rotateY(360deg)";
  z.style.webkitTransform = "rotateY(360deg)";
  z.style.OTransform = "rotateY(360deg)";
  z.style.MozTransform = "rotateY(360deg)";
  }
</script>

这里是整个代码,包括html和javascript:

<!DOCTYPE html>
<html lang="en-US">
    <head>
        <title>animation</title>
        <meta chartset="utf-8">

        <script>
        function ani() {
            var z = document.getElementById("rotate");
            z.style.webkitTransition = "1.2s";
            z.style.transition = "1.2s" ;
            z.style.transform = "rotateY(360deg)";
            z.style.webkitTransform = "rotateY(360deg)";
            z.style.OTransform = "rotateY(360deg)";
            z.style.MozTransform = "rotateY(360deg)";
        }
        </script>
    </head>

    <body>
        <div>
            <p onmouseover="ani()" id="rotate" style="background: rgba(0,0,0,0.5); text-align: center; color: #fff;">Great this is rotating!</p>
        </div>
    </body>
</html>

2 个答案:

答案 0 :(得分:3)

您应该学会制作.css文件并导入它们,而不是在HTML和JavaScript中设置样式。这只是一个很好的做法。

HTML:

<!DOCTYPE html>
<html lang="en-US">
    <head>
        <title>animation</title>
        <meta chartset="utf-8"/>

        <link rel="stylesheet" href="style.css"/>
    </head>
    <body>
        <p id="rotate">Great this is rotating!</p>
    </body>
</html>

CSS(style.css):

#rotate {
    background: rgba(0,0,0,0.5);
    text-align: center;
    color: #fff;
}

#rotate:hover {
    -webkit-transition: 1.2s all;
    transition: 1.2s all;
    -webkit-transform: rotateY(360deg);
    -moz-transform: rotateY(360deg);
    -o-transform: rotateY(360deg);
    transform: rotateY(360deg);
}

JavaScript的:

// Nothing! Fantastic!

答案 1 :(得分:0)

感谢您的所有评论和答案,您启发我。 这就是我所做的,使用其他功能重置样式并使用延迟来等待动画完成@RobG写道。

我使用setInterval()函数来设置延迟,并使用clearInterval()来停止连续执行。

我为我的英语道歉,我没有练习。

   
var z;

function ani(){
 
  z=document.getElementById("rotate");
  z.style.webkitTransition="all 1.2s";
  z.style.transition="all 1.2s" ;
  z.style.transform="rotateY(360deg)";
  z.style.webkitTransform="rotateY(360deg)";
  z.style.OTransform="rotateY(360deg)";
  z.style.MozTransform="rotateY(360deg)";
  
  z.addEventListener("webkitTransitionEnd", unani);
  z.addEventListener("transitionend", unani);

}

function unani(){


  z.style.webkitTransition="";
  z.style.transition="" ;
  z.style.transform="";
  z.style.webkitTransform="";
  z.style.OTransform="";
  z.style.MozTransform="";
 

}