简体   繁体   中英

How to make my header background image randomized on page refresh?

Like the title says, I'm looking for a way to have my webpage's header change to a different image each time I refresh the page. I have 5 .gifs I'm trying to use and I need to use javascript. I'm fairly new to web development, but any help would be appreciated. I also need to know what to put in the css and html but I kind of have an idea where.

If you want to do it all at the client side, ie JavaScript without a server-side language, then you need to provision a few background images.

<div id="header">
...
</div>
...
<script>
bgimgs = ['1.gif', '2.gif', '3.gif', '4.gif', '5.gif'];
pick = Math.round(Math.random()*bgimgs.length)-1;
img=bgimgs[pick];
header=document.getElementById('header');
header.style.background='transparent url('+img+') no-repeat center center';
header.style.backgroundSize='cover';
</script>

Keep the script tag near the end, right before the body tag closes.

Here's a full page for you to start from:

<html>
    <head>
        <script src="https://randojs.com/1.0.0.js"></script>
        <script>
            var headerImages = [
                "rooney.gif",
                "roger.gif",
                "banger.gif",
                "copa90.gif",
                "slop.gif"
            ];

            function showRandomHeaderImage(){
                document.getElementsByTagName("header")[0].style.backgroundImage = "url('" + rando(headerImages).value + "')";
            }
        </script>
        <style>
            body{
                margin:0px;
            }

            header{
                height:50%;
                background-size:cover;
                background-position:center;
                background-repeat:no-repeat;
            }
        </style>
    </head>
    <body onload="showRandomHeaderImage();">
        <header></header>
    </body>
</html>

That way you don't have to worry about what goes where, though the code is pretty simple.

This tag pulls some randomness code from randojs.com so you'll be able to easily and readably do stuff with randomness in your code:

<script src="https://randojs.com/1.0.0.js"></script>

The next script tag allows you to write JavaScript within it in your HTML page, but be aware that the code inside of it will be evaluated before the page loads because we've placed it above the body in our HTML.

<script></script>

I'll explain in a moment how we get code to wait until the body loads to execute. For now let's talk about:

var headerImages = [
    "rooney.gif",
    "roger.gif",
    "banger.gif",
    "copa90.gif",
    "slop.gif"
];

This is an array called headerImages where you store your image filenames. Make it as long or as short as you want.

Now, remember when I said we'd talk about getting script above the body tag to wait until the page loads to execute? The trick is putting it inside a function, like so:

function showRandomHeaderImage(){
    document.getElementsByTagName("header")[0].style.backgroundImage = "url('" + rando(headerImages).value + "')";
}

and then calling it from the onload attribute of the body tag, like so:

<body onload="showRandomHeaderImage();">

There are other ways to achieve this, but this is what I chose. I was trying to explain everything in order from the top of the document to the bottom, but it's important for you to realize that those two spots in the code work together. Let's talk more about the inner workings of the showRandomHeaderImage function:

document.getElementsByTagName("header")[0].style.backgroundImage = "url('" + rando(headerImages).value + "')";

document.getElementsByTagName("header") grabs an array of all header tags on the page, and [0] then selects the first one from that list. Since there's only one header tag on the page, that's great for us. We can then access the "style" attribute of that tag and update the "backgroundImage" within the style attribute to be whatever we want. In your case, you want this to be a random filename from the headerImages array, or:

"url('" + rando(headerImages).value + "')"

You'll notice that grabbing a random image from the headerImages array is pretty simple. No math involved. That's because randojs.com is handling all the stuff for us that's not pretty to read. Visit the website if you want to read up about that. You'll also notice that we attach "url('" to the front of the array value and "')" to the end. This is just because CSS expects background images to be wrapped in that syntax. Then, we have the style tag, within which we can write CSS:

<style></style>

I took away the body's margin so everything within the body can reach the edge of the screen.

body{
    margin:0px;
}

and I made the header 50% of the height of the window and made sure its background images would cover the entire header (even if it has to cut some of it off), center the background image, and not repeat the background image vertically or horizontally.

header{
    height:50%;
    background-size:cover;
    background-position:center;
    background-repeat:no-repeat;
}

...and then comes our body tag, within which we put all of the element tags we want to see on the page, like our header!

<body onload="showRandomHeaderImage();">
    <header></header>
</body>

Remember, that onload attribute is just there to call our function after the page loads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM