如何使用JavaScript来回旋转图像

时间:2015-06-16 23:24:14

标签: javascript html css

我正在尝试创建一个网站,并且在网站上我希望面部旋转到某个点,然后向相反方向旋转直到某一点,如果他们可以继续这样做我想要它但我可以只有让它完全轮换才有人知道如何解决这个问题吗?

这是我的HTML代码:

<!DOCTYPE html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>BSDC</title>
    <link href="style.css" rel="stylesheet" type="text/css" media="all" />
    <script src="jquery-1.10.2.js" type="text/javascript"></script>
    <script>    
        var looper;
        var degrees = 0;
        function rotateAnimation(el,speed){
            var elem = document.getElementById(el);
            if(navigator.userAgent.match("Chrome")){
                elem.style.WebkitTransform = "rotate("+degrees+"deg)";
            } else if(navigator.userAgent.match("Firefox")){
                elem.style.MozTransform = "rotate("+degrees+"deg)";
            } else if(navigator.userAgent.match("MSIE")){
                elem.style.msTransform = "rotate("+degrees+"deg)";
            } else if(navigator.userAgent.match("Opera")){
                elem.style.OTransform = "rotate("+degrees+"deg)";
            } else {
                elem.style.transform = "rotate("+degrees+"deg)";
            }
            looper = setTimeout('rotateAnimation(\''+el+'\','+speed+')',speed);
            degrees++;
            if(degrees > 359){
                degrees = 1;
            }
            document.getElementById("status").innerHTML = "rotate("+degrees+"deg)";
        }
    </script>
</head>
<body>
    <img id="Dave" src="Images/Dave.png"/>
    <script>rotateAnimation("Dave",30);</script>
    <img id="Andy" src="Images/Andy.png" />
    <script>rotateAnimation("Andy",30);</script>
    <img id="Dan" src="Images/Dan.png" />
    <script>rotateAnimation("Dan",30);</script>
    <img id="Nico" src="Images/Nico.png" />
    <script>rotateAnimation("Nico",30);</script>
</body>
</html>

这是我的CSS代码

body {
    font-family: Arial, sans-serif;
    background-image: url("Images/BSDC.png");
    background-repeat: no-repeat;
}
#Dave {
    position: absolute;
    margin-left: 3%;
    margin-top: 3%;
}
#Andy {
    margin-left: 3%;
    margin-top: 35%;
    position: absolute;
}
#Dan {
    margin-left: 85%;
    margin-top: 3%;
    position: absolute;
}
#Nico {
    margin-left: 85%;
    margin-top: 35%;
    position: absolute;
}

1 个答案:

答案 0 :(得分:5)

您可以使用CSS动画完成所有操作。看看这个jsFiddle

浏览器前缀很烦人......如果有人知道这是否可以简化请注释。但这就是概念,你在元素上设置动画:

#box {
  -webkit-animation: NAME-YOUR-ANIMATION 5s infinite; /* Safari 4+ */
  -moz-animation:    NAME-YOUR-ANIMATION 5s infinite; /* Fx 5+ */
  -o-animation:      NAME-YOUR-ANIMATION 5s infinite; /* Opera 12+ */
  animation:         NAME-YOUR-ANIMATION 5s infinite; /* IE 10+, Fx 29+ */
}

然后你定义你的动画,你可以做任何属性更改并尽可能多地执行它,我只使用基本值(0,25,50 100)

@keyframes NAME-YOUR-ANIMATION {
  0%   { transform: rotate(0deg); }
  25% { transform: rotate(45deg); }
  50% { transform: rotate(-45deg); }
  100% { transform: rotate(0deg); }
}

您可以在MDN

上阅读这些内容