how to Randomly rotate images javascript?

2019-07-24 18:57发布

how do i randomly rotate the images without refreshing the page with 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条回答
甜甜的少女心
2楼-- · 2019-07-24 19:32

Just change the src attribute of the image:

<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);

Try it: http://jsfiddle.net/A3v8w/

查看更多
地球回转人心会变
3楼-- · 2019-07-24 19:38

Using JqueryRotate plugin, we can do it easily & more smoothly, with only 1 image

For e.g-

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

http://jsfiddle.net/73pXD/

Ref: jquery-plug-in & codes here .

查看更多
登录 后发表回答