Randomly displaying images is a very widely used technique. For example, random banners are displayed. When you enter a website, its banner is always different, or there are always tips with different content. You will often find such examples when browsing the Internet. Using this technology, not only can more content be put into a certain space, but it can also give people the illusion of frequent updates.
How excited are you? In fact, as long as you have a little basic knowledge of html and javascript, everything is so simple. follow me and let's take a look at her random secrets.
Let's start with a simple example. Usually we add pictures to the page using <img src="picture">. If we want to randomly display 3 different pictures, we need to make a small modification to this code. First, add the <script> tag:
The following is a quoted fragment:
<script language=javascript></script>
Then put <img src="picture"> in this tag using document.write(""), and it becomes
document.write("<img src=image>")
Now let’s finish the most critical paragraph:
Here is the quote:
id=Math.round(Math.random()*2)+1
In this way, the random numbers are obtained as 1, 2, and 3. Rename the picture you want to display to 1.gif, 2.gif, 3.gif, ok! The final code is:
Here is the quote snippet:
<script language=javascript>
id=Math.round(Math.random()*2)+1
document.write("<img src="+id+".gif>")
</script>
Give it a try, isn’t it good? So what if each of my pictures corresponds to a hyperlink?
Let's assume that there are 3 pictures, 1.gif, 2.gif, 3.gif, and the corresponding links are url1, url2, and url3.
In order to have a one-to-one correspondence between images and links, we need to set up an array image to place the address of the link, as follows:
The following is a reference fragment:
var image=new Array(3)
image.length=3
image[1]="url1"
image[2]="url2"
image[3]="url3"
In order to get the link corresponding to the image, we also need to define an array imageurl=image[id]
The principle is this:
When the page is read, a random number is taken, assuming it is 2, that is, id=2, then we can easily display 2.gif on the page as above. Then we can see: imageurl=image[2] and image[2]="url2", the rest is easy. The complete code is as follows:
The following is a quoted fragment:
<script language=javascript>
var image=new Array(3)
image.length=3
image[1]="url1"
image[2]="url2"
image[3]="url3"
id=Math.round(Math.random()*2)+1
imageurl=image[id]
document.write("<a href="+bannerurl+">"+"<img src="+id+".gif>")
</script>
Reprinted from: Seven Color Bird Design---pc-king