Home > Web Front-end > JS Tutorial > body text

js实现网页随机切换背景图片的方法_javascript技巧

WBOY
Release: 2016-05-16 16:32:20
Original
2226 people have browsed it

本文实例讲述了js实现网页随机切换背景图片的方法。分享给大家供大家参考。具体实现方法如下:

首先要准备一些图像,图像的大小(无论是尺寸大小还是数据大小)要控制好,如果太大,会使用户等不及查看全图就跳出了,如果太小,又会影响页面质量

在script中将这些图像编为一个数组,便于调用。数组的长度当然就是图像的数量。

复制代码 代码如下:
var bodyBgs = [];    //创建一个数组变量来存储背景图片的路径
bodyBgs[0] = "images/01.jpg";
bodyBgs[1] = "images/02.jpg";
bodyBgs[2] = "images/03.jpg";
bodyBgs[3] = "images/04.jpg";
bodyBgs[4] = "images/05.jpg";

因为上面用到了5个图像,所以在这里需要产生一个0到4的随机数。如果数组长度不一样,修改下面代码中的乘数就可以。

复制代码 代码如下:
var randomBgIndex = Math.round( Math.random() * 4 );

核心的程序就是这些。尽管很简单,却是一种小小的思路,若以此为基础,通过加工可以做出一些扩展功能。比如:主题切换以及其它的随机呈现等等。下面是完整的JS代码。

复制代码 代码如下:

希望本文所述对大家基于javascript的web程序设计有所帮助。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!