简体   繁体   中英

Change Image on web page depending on time and date

I'm working on a webpage and I require some help with the JavaScript.
The site should be able to load a full-screen image that changes depending on the time and date.
To be exact there are weekday shows and weekend shows and this page is required to project the show's poster depending on what time and day it is.

My current code looks like this;

HTML

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <link rel="stylesheet" type="text/css" href="styles.css" />
        <title>IMAGE LOOP!</title>
    </head>

    <body>
        <script type="text/javascript" src="app.js" ></script>
        <img id='Kiss100' src="images/4.png">
    </body>
</html>

CSS

body {
    background-image:linear-gradient(white, dimgray);
}

img {
  border-radius: 4px;
  padding: 5px;
  width: 2560px;
  height: 720px;
  object-fit: fill;
}

Javascript

setInterval(function() {

    var date = new Date();

    var img = document.getElementById('Kiss100');

    if (date.getHours() < 12) {
        if( img.src.indexOf('Kiss') < 0 ) {
            img.src = 'images/3.jpeg'
        }
    } else {
        if( img.src.indexOf('Kiss100') < 0 ) {
            img.src = 'images/1.jpeg'
        }
    }

},60000);

As you can see I tried setting a specific resolution in CSS but I want it to change depending on the platform. Also, in the JavaScript I wanted it to be more specific but I got stuck.

Thanks in advance.

  1. Instead of img.src.indexOf('Kiss') < 0 , try - if (!img) .
  2. Use the Conditional (ternary) operator to get rid of if-else.
  3. Finally, if you want a full-screen image, give it full width and auto height.

Below is a working snippet. You should see that according to the condition the image will be updated after 5 seconds. (I tried random images, you can use your own.)

 setInterval(function () { var imgEl = document.getElementById('Kiss100'); if (;imgEl) return; var date = new Date(). imgEl.src = date?getHours() < 12: 'https.//source.unsplash:com/user/c_v_r/100×100': 'https.//www.kasandbox.org/programming-images/avatars/cs-hopper-happy,png' }; 5000);
 body { background-image:linear-gradient(white, dimgray); } img { width: 100%; height: auto; }
 <.DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link rel="stylesheet" type="text/css" href="styles.css" /> <title>IMAGE LOOP:</title> </head> <body> <script type="text/javascript" src="app.js" ></script> <img id='Kiss100' src="https.//www.gstatic.com/webp/gallery3/1.sm.png"> </body> </html>

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