如何更改<input type =“Date”/>的特定日期的颜色?

时间:2018-02-26 13:06:05

标签: jquery css html5 date calendar

有没有办法改变HTML 5的输入类型日期的样式(即颜色) 在html 5中,我们可以通过<input type=date>显示日历 现在可以说3月23日是假日,我想用红色显示这个特定的日期,我该怎么做?

我想在打开日历时更改特定日期的颜色,以便客户可以看到它,就像我在下面的图片enter image description here

中使用Jquery插件实现的那样

3 个答案:

答案 0 :(得分:-1)

以下是jQuery的方法。

   $('input[type="date"]').change(function{    
        var date = new Date( this.value );
        var specificDate = "23 March 2018";
        if(date.getDay() == 6 || date.getDay() == 0 ||  this.value == specificDate) { //Check for Saturday or Sunday
           $(this).css("color","red"); 
        }
        else {
           $(this).css("color","inherit"); 
        }
    });

答案 1 :(得分:-1)

纯js解决方案,不需要jQuery。您可以将假期保存在数组中,并检查输入是否在数组中。

参考 1. includes 2. Date comparison

&#13;
&#13;
function datechanged(el) {
    var holiday = new Date("2018-10-02");
    var holidays = [new Date("2018-10-02").getTime(), new Date("2018-02-02").getTime(), new Date("2018-02-01").getTime()]

    var inputDate = new Date(el.value);
    el.classList.remove("red");

    if(holidays.includes(inputDate.getTime())){
      el.classList.add("red")
    }
}
&#13;
/* Styles go here */

.red{
  color:red;
}
&#13;
<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

  <body>
    <input type=date onchange="datechanged(this)">
  </body>

</html>
&#13;
&#13;
&#13;

答案 2 :(得分:-1)

我会创建一个包含特定日期的数组。有了它,您可以定位输入的更改。并根据它在数组中找到它来更改类。

我使用indexOf()并在结果与 -1

不同时更改课程

希望这就是你要找的东西。如果需要,很乐意解释或帮助提供更好的解决方案。

&#13;
&#13;
const redDates = ['2018-02-26','2018-03-26'];
$('input').change(function() {

  $(this).removeClass('holiday');
  if(redDates.indexOf($(this).val()) != -1)
    $(this).addClass('holiday');

})
&#13;
.holiday {
color: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="date">
&#13;
&#13;
&#13;

相关问题