1

我制作了这个小对象,它可以根据两个变量让您知道一个地方是否开放。但是我想让它变得更好,因为我不太擅长 javascript 我想知道什么是最佳实践。我将如何为在关闭或打开前一分钟到达那里的用户实时更新打开/关闭状态。

CodePen 源代码

html

<h1 class="status"></h1>
<h2 class="hours"></h2>

css

body {
  color: white; 
  text-align: center;
  font-size: 2em;
}

.open   { background-color: #00a638; }
.closed { background-color: black; }

js

// variables
var open = "7:00";
var close = "5:00";

// setup miliary time
var mClose = close.replace(/:/g,'') + 1200;
var mOpen = open.replace(/:/g,'');

if (mOpen < 1000) {
  mOpen = "0" + mOpen;
}

// setup hours
var now = new Date();
var hour = now.getHours();
if (hour >= 10) { mHour = hour; 
  } else { mHour = "0" + hour; }

// setup minutes
var minute = now.getMinutes();

if (minute < 10) {
  minute = "0" + minute;
}

var time = "" + mHour + minute;
console.log("Time is " + time);

// open/close status
if ((time >= mOpen) && (time < mClose)) {
 $("body").addClass("open");
 $(".status").html("Yes, We're Open");
} else {
 $("body").addClass("closed");   
 $(".status").html("Sorry We're Closed");
}

// display hours
$(".hours").html(open + " to " + close);
4

0 回答 0