创建一个点击改变网站的背景图片 [英] Create website background image that changes on a click

查看:107
本文介绍了创建一个点击改变网站的背景图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何创建一个背景图像点击时会改变。它应该通过这样的图像序列。任何线索如何使这个?

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?

推荐答案

这是一个基本的jQuery的解决方案:

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] ) + "')";
  });
});

演示: http://jsbin.com/isubag/2/edit

这解决方案是jQuery的,这将慢下来只是有点pretty沉重。你可以有一个更全面的方法去。不幸的是,仍然使用 $的。inArray (虽然<一个href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf#Compatibility\"相对=nofollow> polyfills确实存在),至于的indexOf 阵列上是不是所有的伟大。

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

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

这篇关于创建一个点击改变网站的背景图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆