Create website background image that changes on a

2019-09-20 00:06发布

I am wondering how to create a background image that will change when clicked. It's supposed to go through a sequence of images like this. Any clues how to make this?

1条回答
ゆ 、 Hurt°
2楼-- · 2019-09-20 01:02

The jQuery Way

Here's a basic jQuery solution:

var images = [
  'http://placekitten.com/500/500',
  'http://placekitten.com/400/400',
  'http://placekitten.com/750/750'
];

$(".changeBG").on("click", function(){
  $("body").css("backgroundImage", function( o, v ) {
    var backg = v.match( /\((.+)\)/ );
    var index = $.inArray( ( backg ? backg[1] : "" ), images );
    return "url('" + ( images[++index] || images[0] ) + "')";
  });
});

Demo: http://jsbin.com/isubag/2/edit

The Pure JavaScript (almost) Way

That solution is pretty heavy on the jQuery, which will slow it down just a bit. You could go with a far more holistic approach. Unfortunately there is still the use of $.inArray (though polyfills do exist), as native support for indexOf on arrays isn't all that great.

var bg = {
  images: [
    'http://placekitten.com/500/500',
    'http://placekitten.com/400/400',
    'http://placekitten.com/750/750'
  ],
  get: function () {
    var match = document.body.style.backgroundImage.match( /\((.+)\)/ );
    return match ? match[1] : "" ;
  },
  set: function ( url ) {
    document.body.style.backgroundImage = "url('" + url + "')" ; 
  }
};

function bgCycler () {
  var index = $.inArray( bg.get(), bg.images );
  bg.set( bg.images[++index] || bg.images[0] );
}

Demo: http://jsbin.com/isubag/edit#javascript,html

查看更多
登录 后发表回答