[英]Continuous rotation of image on button click using Javascript
我希望圖像每隔1秒旋轉一次。我使用了以下代碼,但是它不起作用。 我的代碼是:-
<html>
<head>
<style>
.rotated-image
{
-webkit-transform: rotate(2deg);
transform: rotate(2deg);
}
</style>
</head>
<body>
<section id="middle">
<img id="image" src="1.png" >
<button onclick="myFunction()">Click me</button>
</section>
<script>
function myFunction()
{
var img = document.getElementById("image");
img.setAttribute("class", "rotated-image");
setTimeout("myFunction()",1000);
}
</script>
</body>
</html>
您可以使用純CSS做到這一點。 嘗試這個:
<style>
@-webkit-keyframes animate-rotate{
from {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
to {
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
}
}
@-keyframes animate-rotate{
from {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
to {
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
}
}
.rotated-image
{
-webkit-animation: animate-rotate 180s infinite;
animation: animate-rotate 180s infinite;
}
</style>
function myFunction()
{
var img = document.getElementById("image");
img.setAttribute("class", "rotated-image");
}
試試這個
var deg = 2; // starting
var rotation_diff = 30; // you can change it to 2 if you want to rotate 2 deg in each second
function myFunction()
{
var img = document.getElementById("image");
img.style.webkitTransform = "rotate("+deg+"deg)";
img.style.transform = "rotate("+deg+"deg)";
img.style.MozTransform = "rotate("+deg+"deg)";
img.style.msTransform = "rotate("+deg+"deg)";
img.style.OTransform = "rotate("+deg+"deg)";
setTimeout("myFunction()",1000);
deg = deg + rotation_diff;
}
更新2:
對於開始和停止
HTML
<img id="image" src="http://static.kuikr.com/images/quikr_logo_f3.png" >
<button onclick="start()">Start</button>
<button onclick="stop()">Stop</button>
JAVASCRIPT
var deg = 2; // starting
var rotation_diff = 30;
var rotation;
function start()
{
rotation=1;
myFunction();
}
function stop()
{
rotation=0;
}
function myFunction()
{
var img = document.getElementById("image");
img.style.webkitTransform = "rotate("+deg+"deg)";
img.style.transform = "rotate("+deg+"deg)";
img.style.MozTransform = "rotate("+deg+"deg)";
img.style.msTransform = "rotate("+deg+"deg)";
img.style.OTransform = "rotate("+deg+"deg)";
if(rotation==1) {
setTimeout("myFunction()",1000); }
deg = deg + rotation_diff;
}
參見更新字段
var ss = 2;
function myFunction() {
ss = ss + 1;
$("#image").css({
'-webkit-transform': 'rotate(' + ss + 'deg)',
'-moz-transform': 'rotate(' + ss + 'deg)'
});
setTimeout("myFunction()", 1000);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.