页面刷新时随机更改HTML背景 [英] Change HTML Background randomly on page refresh

查看:493
本文介绍了页面刷新时随机更改HTML背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道已经讨论了很多主题,但是我希望我的主页随机选择一个图像,然后更改该图像的字幕.我网站的URL是: http://www.connorloughlin.com

I know this topic has been looked at loads of times, but I would like my home page to randomly select an image and then change the subtitle for that image. The URL for my site is: http://www.connorloughlin.com

页面底部是一个小标题,如果更改了相关背景,将非常有用.如果太复杂,我不会打扰,但认为它看起来不错!最好我有5张图片,每张图片都有自己的字幕.

At the bottom of the page is a little subtitle, would be great if it changed for the relevant background. If it's too complex I won't bother but thought it'd look good! Preferably i'd have 5 images each with their own subtitle.

让我知道您是否要澄清任何事情,并在此先感谢!

Let me know if you want me to clarify anything and thanks in advance!

推荐答案

由于您使用的是jQuery,因此我使用了该版本: http://jsbin.com/OQugAMI/4/edit

Since you're using jQuery, I've made a version using that: http://jsbin.com/OQugAMI/4/edit

1)创建一个包含图像列表的数组&字幕

1) create an Array containing the list of images & subtitles

    var backgrounds = [
  {  image: 'http://www.connorloughlin.com/images/background.jpg',
   subtitle: 'Looking out at Carcassonne, France - August 2013'
  },
  {  image: 'http://upload.wikimedia.org/wikipedia/commons/1/13/1632x1224_sertaoe_2_rio_grande_do_norte_landscape_panorama_brasil.jpg',
   subtitle: 'Version 2'
  },
  {  image: 'http://upload.wikimedia.org/wikipedia/commons/7/71/1632x1224_sertaoe_rio_grande_do_norte_landscape_panorama_brasil.jpg',
   subtitle: 'Version 3'
  }
       ]; 

2)从该阵列中选择一个随机图像

2) select a random image from that array

/**
 * Returns a random integer between min and max
 * Using Math.round() will give you a non-uniform distribution!
 * http://stackoverflow.com/questions/1527803/generating-random-numbers-in-javascript-in-a-specific-range
 */
function getRandomInt (min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

$(document).ready(function(){
    var bgNumber = getRandomInt(0, backgrounds.length-1);
}

3)更新H4&正文CSS来反映选择

3) update the H4 & body CSS to reflect the choice

$('body').css('background-image', 'url('+backgrounds[bgNumber].image+')');
$('h4').html(backgrounds[bgNumber].subtitle);

这将选择一个新图像&每个页面上的字幕加载

This will pick a new image & subtitle on each page load

这篇关于页面刷新时随机更改HTML背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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