最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Change background image based on the hour

programmeradmin4浏览0评论
Closed. This question is off-topic. It is not currently accepting answers.

Your question should be specific to WordPress. Generic PHP/JS/SQL/HTML/CSS questions might be better asked at Stack Overflow or another appropriate Stack Exchange network site. Third-party plugins and themes are off-topic for this site; they are better asked about at their developers' support routes.

Closed 4 years ago.

Improve this question

I'm triying to change my row background image based on the hour of the day. I want to show an imagen from 08:00 to 18:00 and another for the night. Can anyone help me? I know that I need to use JS but I don't know to implement it well.

Thanks!

Closed. This question is off-topic. It is not currently accepting answers.

Your question should be specific to WordPress. Generic PHP/JS/SQL/HTML/CSS questions might be better asked at Stack Overflow or another appropriate Stack Exchange network site. Third-party plugins and themes are off-topic for this site; they are better asked about at their developers' support routes.

Closed 4 years ago.

Improve this question

I'm triying to change my row background image based on the hour of the day. I want to show an imagen from 08:00 to 18:00 and another for the night. Can anyone help me? I know that I need to use JS but I don't know to implement it well.

Thanks!

Share Improve this question asked Sep 19, 2020 at 14:58 sarasara 1
Add a comment  | 

1 Answer 1

Reset to default 2

This question isn't WordPress specific so is perhaps better for StackOverflow instead. We can make it WordPress specific by suggesting the use of wp_enqueue_script to add the script to the page, but ultimately this is a JavaScript question.

I'm basing my answer off of this article

// Get the local time of the visitor
var localTime = new Date();
var localHour = localTime.getHours();
            
// Bool to determine if it is night or day
var isNight = ( 18 <= localHour || 8 >= localHour ) ? true : false;
            
// Object containing URL links to images 
const  backgroundURLs = {
    day: 'https://placekitten/1960/1960',
    night: 'https://placekitten/1961/1961',
};
                
// Sets the background image
const setBackground = (image) => {
  // wait for window to be loaded to ensure body is present, 
  // if you are checking this elsewhere you can remove the window.onload check
  window.onload = function() {
     document.body.style.background = "url('"+backgroundURLs[image]+"')";
  }
};
            
// Actually set the background based on the bool and URL object. 
if ( isNight ) {
  setBackground('night');
} else {
  setBackground('day');
}
发布评论

评论列表(0)

  1. 暂无评论