我正在尝试在我的网站上发布营业时间,并且希望根据 JavaScript 自动将日期和时间加粗。是否可以设置一些 JavaScript,以便星期一加粗,然后星期二加粗,依此类推?
这是代码:
<div id="monday">Monday: 12:00-2:00</div>
<div id="tuesday">Tuesday: 11:00-3:00</div>
每天依此类推。当用户在星期一访问该网站时,我希望星期一的 div 将其中的所有内容加粗。当用户在星期二访问该网站时,我希望整个星期二 div 变为粗体。
谢谢
最佳答案
像这样:
示例: http://jsfiddle.net/c5bHx/
<!DOCTYPE html>
<html>
<head><title>title</title></head>
<body>
<!-- your content -->
<!-- place this just inside your closing </body> tag -->
<script type="text/javascript>
var days = 'sunday,monday,tuesday,wednesday,thursday,friday,saturday'.split(',');
document.getElementById( days[(new Date()).getDay()] ).className = 'bold';
</script>
</body>
</html>
CSS
.bold {
font-weight:bold;
}
<小时/>
编辑:
以下是所发生事件的详细说明。我将使其更加详细,将代码扩展到不同的变量中,以便更容易查看。
// This simply creates a string of days in the week
var days = 'sunday,monday,tuesday,wednesday,thursday,friday,saturday';
// This splits the string on the commas, turning it into an Array of weekdays
days = days.split(',');
// Create a new Date object, representing today's date and time
var date = new Date();
// Get the number of the day of the week. 0 if sunday, 1 if monday, etc...
var dayNumber = date.getDay();
// Using the "dayNumber", get the day string by its index from the "days" array
var dayString = days[ dayNumber ];
// Select the element on the page that has the ID that matches the "dayString"
var dayElement = document.getElementById( dayString );
// Set the "class" property of the "dayElement" to the "bold" class.
dayElement.className = "bold";
请注意,不需要将日期字符串转换为数组。只是更短一些并且打字更快。
你可以这样做:
var days = ['sunday','monday','tuesday','wednesday','thursday','friday','saturday'];
这会创建一个数组,因此您不需要执行 .split()
。
关于javascript - 如何使用 javascript 将日期和时间加粗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4824454/