随机化图像以显示在主页背景上

时间:2018-04-11 22:38:25

标签: jquery html css image background-image

每当有人访问主页时,我如何更改背景图片?当前的背景图像是在CSS中控制的,而不是HTML,因此非常感谢任何帮助。

请参阅CSS了解单个背景图片:

 header .container-fluid
 {
 background-image: url("../../images/The Connection at St-Martin-in-the- 
 Fields/Carousel image - med res The Connection -1067838.jpg");
 background-repeat: no-repeat;
 background-size: cover;
 height: 100vh;
 padding-top: 36px;
 }

1 个答案:

答案 0 :(得分:0)

只需在页面中添加一点JavaScript即可更改页面加载时的图片:

// make a list of images to select from
var images = ['cat.jpg', 'dog.jpg'];

// find the element whose background image you want to change
var elem = document.querySelector('header .container-fluid');

// get the index position of the image in `images` to be displayed
var index = Math.floor(Math.random() * images.length);

// set the background image property
elem.style.backgroundImage = 'url(' + images[index] + ')';

JavaScript设置的背景图像优先于CSS样式,因此将显示由JavaScript设置的图像。