【问题标题】:How to change color of specific Date of <input type=Date>? [duplicate]如何更改 <input type=Date> 的特定日期的颜色? [复制]
【发布时间】:2018-08-05 22:53:08
【问题描述】:

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

我想在打开日历时更改特定日期的颜色,以便客户端可以看到它,就像我在下图中使用 Jquery 插件实现的那样

【问题讨论】:

  • 你在使用 jquery 日期选择器吗?
  • 我没有使用任何插件,
  • 您可以使用 jquery 日期选择器并像这样更改日期颜色 codepen.io/SaurabhShine/pen/MQPBKp
  • @Overflowrun 那问题是完全不同的伙伴
  • 好的,所以我错误地理解了这个问题,因为下面的所有答案......你想要的实际上是不可能的,没有办法设置日历的样式,你只能设置输入的样式

标签: jquery css html date calendar


【解决方案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"); 
        }
    });

【讨论】:

    【解决方案2】:

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

    使用了indexOf(),当结果与-1

    不同时会改变类

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

    const redDates = ['2018-02-26','2018-03-26'];
    $('input').change(function() {
    
      $(this).removeClass('holiday');
      if(redDates.indexOf($(this).val()) != -1)
        $(this).addClass('holiday');
    
    })
    .holiday {
    color: red;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="date">

    【讨论】:

      【解决方案3】:

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

      参考 1.includes 2.Date comparison

      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")
          }
      }
      /* Styles go here */
      
      .red{
        color:red;
      }
      <!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>

      【讨论】:

        猜你喜欢
        • 2020-10-28
        • 2023-03-23
        • 2013-07-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-01
        • 2018-10-05
        • 2013-06-25
        相关资源
        最近更新 更多