The method of _javascript the background picture of the random Web page in JS technique

Source: Internet
Author: User
Tags array length

This paper illustrates the method of the random handover of the background image of JS Web page. Share to everyone for your reference. The implementation methods are as follows:

First of all to prepare some images, the size of the image (whether size or data size) to control, if too large, users can not wait to see the whole picture jumped out, if too small, will affect the quality of the page

Make these images an array in script for easy invocation. The length of the array is, of course, the number of images.

Copy Code code as follows:
var bodybgs = []; Create an array variable to store the path of the background picture
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";

Because it uses 5 images, you need to generate a random number from 0 to 4 here. If the array length is not the same, modify the multiplier in the following code.

Copy Code code as follows:
var randombgindex = Math.Round (Math.random () * 4);

The core process is these. Although very simple, but is a small idea, if on this basis, through processing can make some extension functions. For example: Theme switching and other random rendering, and so on. The following is the complete JS code.

Copy Code code as follows:
<script type= "Text/javascript" >
<! cdata[
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";
var randombgindex = Math.Round (Math.random () * 4);
Output a random background image
document.write (' <style>body{background:url (' + bodybgs[randombgindex] + ') no-repeat 50% 0}</style> ');
]]>
</script>

I hope this article will help you with your JavaScript based web design.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.