Using JS operation CSS to implement JS change background picture Example

Source: Internet
Author: User

A friend on the Weibo asked me if you can use JS and CSS to make every refresh of the page randomly generated a background map, of course, it is possible. See the following implementation code in concrete ways

1, with JS to define an image array, which store you want to randomly display the picture code as follows: Ar imgarr=["http://www.jb51.net/logo_cn.png", "http://www.jb51.net/baidu_ Sylogo1.gif "," http://www.jb51.net/news/uploadImg/20120111/20120111081906_79.jpg "," http://www.jb51.net/news/   Uploadimg/20120111/20120111081906_76.jpg "];   Please change the picture above for your own.     2, with JS to generate a random number, of course, this random number from the beginning of 0 to imgarr.length-1 end code as follows: Var index =parseint (Math.random () * (imgarr.length-1));     So we get the current randomly generated picture code as follows: Var currentimage=imgarr[index];   3, since a random generation of a background map, then use JS to this picture as a background map.     The code is as follows: document.getElementById ("Backgroundarea"). Style.backgroundimage= "url (" +currentimage+ ")";    Since this is a demo, I have defined a div with ID backgroundarea on the page, and also set a random background for this div. The code is as follows: <div id= "Backgroundarea" > </div>
Related Article

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.