javascript - 如何使用 javascript 将日期和时间加粗

标签 javascript

我正在尝试在我的网站上发布营业时间,并且希望根据 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/

相关文章:

javascript - Backbone.js - 如何在模板中使用自定义模型属性?

javascript - 在 Scss Functions Angular 中动态添加 $theme-colors 颜色

Javascript 类型错误 : result of expression is not an object

javascript - 使用悬停功能,Jquery 在随机位置生成 div

javascript - MongoDB错误: Cannot create property '_id' on string

javascript - php 回显的动态 javascript 不起作用

JavaScript 请求 JSON 信息。返回错误结果

javascript - document.getElementById ('blah' ).value 的行为不符合预期

javascript - 无法在 Windows 8 平板电脑中上传文件

javascript - 使用 jQuery 隐藏和显示数据列表的更多行