如何随机旋转图像javascript?

时间:2011-10-25 07:33:36

标签: javascript settimeout

如何在不使用setTimeout ??

刷新页面的情况下随机旋转图像

JS:

  var bannerImages = new Array( );

  bannerImages[0] = "Banner1.jpg";
  bannerImages[1] = "Banner2.jpg";
  bannerImages[2] = "Banner3.jpg";
  bannerImages[3] = "Banner4.jpg";

  var randomImageIndex = Math.round( Math.random( ) * 3 );
  document.write( "<img alt=\"\" src=\"imgs/" + bannerImages[randomImageIndex] + "\">" );

`

2 个答案:

答案 0 :(得分:2)

只需更改图片的src属性:

<img id="pic" src="http://jsfiddle.net/favicon.png" />

function changeImage()
{
    var bannerImages = new Array( );

    bannerImages[0] = "http://jsfiddle.net/favicon.png";
    bannerImages[1] = "http://jsfiddle.net/img/logo.png";
    bannerImages[2] = "http://jsfiddle.net/img/info-close.png";

    var image = document.getElementById('pic');
    var randomImageIndex = Math.floor( Math.random( ) * bannerImages.length );
    image.src = bannerImages[randomImageIndex];
}
window.setInterval(changeImage, 1000);

试一试:http://jsfiddle.net/A3v8w/

答案 1 :(得分:0)

使用JqueryRotate插件,我们可以轻松地完成它更顺畅,只有1张图片

例如 -

var angle = 0;
setInterval(function(){
      angle+=3;
     $("#img").rotate(angle);
},50);

<强> http://jsfiddle.net/73pXD/

参考: jquery-plug-in &amp; codes here