在网页设计中,背景图片是一个很关键的元素,可以为网页营造出不同的氛围。但是,单一的背景图片会让网页显得乏味,因此我们可以通过CSS来实现背景随机切换的效果。下面我们来看看具体的实现方法。
<html> <head> <style> body { background: url(images/1.jpg) center center fixed no-repeat; background-size: cover; } /* 定义背景图片数组 */ var bg = [ "url(images/2.jpg)", "url(images/3.jpg)", "url(images/4.jpg)", "url(images/5.jpg)", "url(images/6.jpg)" ]; /* 得到一个0到图片数量之间的随机整数 */ var index = Math.floor(Math.random() * bg.length); /* 应用随机背景图片 */ body.style.background = bg[index] + "center center fixed no-repeat"; body.style.backgroundSize = "cover"; </style> </head> <body> <h1>这是一个随机背景切换的例子</h1> </body> </html>
通过上面的代码,我们可以实现随机切换背景的效果。由于我们将背景图片存储到一个数组中,因此每次刷新网页时都会随机选取一个不同的图片作为背景。这样就有助于为网页营造更加生动的氛围。