jQuery 如何让所有浏览器都支持 <input type="date">?任何替代方案?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18020950/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:22:52  来源:igfitidea点击:

How to make <input type="date"> supported on all browsers? Any alternatives?

javascriptjqueryhtmljquery-ui

提问by leonardeveloper

I'm working with HTML5 elements input attributes and only Google Chrome supports the date, time attributes. I tried Modernizrbut I can't understand on how to integrate it on my website(on how to code it/what is the syntax/includes). Any code snippet there on how to work with date, time attributes to all browsers.

我正在使用 HTML5 元素输入属性,只有 Google Chrome 支持日期、时间属性。我尝试了Modernizr,但我无法理解如何将它集成到我的网站上(关于如何对其进行编码/什么是语法/包含)。关于如何处理所有浏览器的日期、时间属性的任何代码片段。

回答by adeneo

Any browser that does not support the input type datewill default to the standard type, which is text, so all you have to do is check the type property(not the attribute), if it's not date, the date input is not supported by the browser, and you add your own datepicker:

任何不支持输入类型的浏览器都date将默认为标准类型,即text,因此您要做的就是检查 type属性(而不是属性),如果date不支持,则浏览器不支持日期输入,然后添加自己的日期选择器:

if ( $('[type="date"]').prop('type') != 'date' ) {
    $('[type="date"]').datepicker();
}

FIDDLE

小提琴

You can of course use any datepicker you want, jQuery UI's datepicker is probably the one most commonly used, but it does add quite a bit of javascript if you're not using the UI library for anything else, but there are hundreds of alternative datepickers to choose from.

您当然可以使用任何您想要的日期选择器,jQuery UI 的日期选择器可能是最常用的一个,但如果您不将 UI 库用于其他任何用途,它确实会添加相当多的 javascript,但有数百种替代日期选择器从中选择。

The typeattribute never changes, the browser will only fall back to the default texttype for the property, so one has to check the property.
The attribute can still be used as a selector, as in the example above.

type属性永远不会改变,浏览器只会回退到text该属性的默认类型,因此必须检查该属性。
该属性仍可用作选择器,如上例所示。

回答by jfmatt

Modernizr doesn't actually change anything about how the new HTML5 input types are handled. It's a feature detector, not a shim (except for <header>, <article>, etc., which it shims to be handled as block elements similar to <div>).

Modernizr 实际上并没有改变新的 HTML5 输入类型的处理方式。这是一个特征检测,而不是一个垫片(除<header><article>等等,其作为衬层块元素类似于待处理<div>)。

To use <input type='date'>, you'd need to check Modernizr.inputtypes.datein your own script, and if it's false, turn on another plugin that provides a date selector. You have thousands to choose from; Modernizr maintains a non-exhaustive list of polyfillsthat might give you somewhere to start. Alternatively, you could just let it go - all browsers fall back to textwhen presented with an input type they don't recognize, so the worst that can happen is that your user has to type in the date. (You might want to give them a placeholder or use something like jQuery.maskedinput to keep them on track.)

要使用<input type='date'>,您需要签Modernizr.inputtypes.date入自己的脚本,如果它是错误的,请打开另一个提供日期选择器的插件。您有数千种可供选择;Modernizr 维护了一个 polyfills 的非详尽列表,它们可能会给你一个开始的地方。或者,您可以放手一搏——所有浏览器text在出现它们无法识别的输入类型时都会回退,因此可能发生的最糟糕的情况是您的用户必须输入日期。(你可能想给他们一个占位符或使用类似 jQuery.maskedinput 的东西来让他们保持正轨。)

回答by Tim S

You asked for Modernizr example, so here you go. This code uses Modernizr to detect whether the 'date' input type is supported. If it isn't supported, then it fails back to JQueryUI datepicker.

你问了 Modernizr 的例子,所以你去。此代码使用 Modernizr 来检测是否支持“日期”输入类型。如果它不受支持,则它会失败返回到 JQueryUI 日期选择器。

Note: You will need to download JQueryUI and possibly change the paths to the CSS and JS files in your own code.

注意:您需要下载 JQueryUI,并可能在您自己的代码中更改 CSS 和 JS 文件的路径。

<!DOCTYPE html>
<html>
    <head>
        <title>Modernizer Detect 'date' input type</title>
        <link rel="stylesheet" type="text/css" href="jquery-ui-1.10.3/themes/base/jquery.ui.all.css"/>
        <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/modernizr/modernizr-1.7-development-only.js"></script>
        <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
        <script type="text/javascript" src="jquery-ui-1.10.3/ui/jquery.ui.core.js"></script>
        <script type="text/javascript" src="jquery-ui-1.10.3/ui/jquery.ui.widget.js"></script>
        <script type="text/javascript" src="jquery-ui-1.10.3/ui/jquery.ui.datepicker.js"></script>
        <script type="text/javascript">
            $(function(){
                if(!Modernizr.inputtypes.date) {
                    console.log("The 'date' input type is not supported, so using JQueryUI datepicker instead.");
                    $("#theDate").datepicker();
                }
            });
        </script>
    </head>
    <body>
        <form>
            <input id="theDate" type="date"/>
        </form>
    </body>
</html>

I hope this works for you.

我希望这对你有用。

回答by Ritabrata Gautam

   <script>
      var datefield = document.createElement("input")
      datefield.setAttribute("type", "date")
      if (datefield.type != "date") { // if browser doesn't support input type="date", load files for jQuery UI Date Picker
         document.write('<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />\n')
         document.write('<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"><\/script>\n')
         document.write('<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"><\/script>\n')
      }
   </script>

 <script>
    if (datefield.type != "date") { // if browser doesn't support input type="date", initialize date picker widget:
       jQuery(function($) { // on document.ready
           $('#birthday').datepicker();
       }); <- missing semicolon
    }
 </script>

<body>
 <form>
   <b>Date of birth:</b>
   <input type="date" id="birthday" name="birthday" size="20">
   <input type="button" value="Submit" name="B1">
 </form>
</body>

SOURCE 1& SOURCE 2

来源 1来源 2

回答by Antti Haapala

This is bit of an opinion piece, but we had great success with WebShims. It can decay cleanly to use jQuery datepicker if native is not available. Demo here

这有点像评论文章,但我们在WebShims 上取得了巨大的成功。如果本机不可用,它可以完全衰减以使用 jQuery datepicker。演示在这里

回答by Rápli András

Just use <script src="modernizr.js"></script>in the <head>section, and the script will add classes which help you to separate the two cases: if it's supported by the current browser, or if it's not.

只需<script src="modernizr.js"></script>在该<head>部分中使用,脚本就会添加类来帮助您区分两种情况:当前浏览器是否支持,或者不支持。

Plus follow the links posted in this thread. It will help you: HTML5 input type date, color, range support in Firefox and Internet Explorer

加上在此线程中发布的链接。它将帮助您:Firefox 和 Internet Explorer 中的 HTML5 输入类型日期、颜色、范围支持

回答by Kelvin

Chrome Version 50.0.2661.87 m does not support the mm-dd-yy format when assigned to a variable. It uses yy-mm-dd. IE and Firefox work as expected.

Chrome 版本 50.0.2661.87 m 在分配给变量时不支持 mm-dd-yy 格式。它使用 yy-mm-dd。IE 和 Firefox 按预期工作。

回答by Kashif Latif

best easy and working solution i have found is, working on following browsers

我发现的最好的简单可行的解决方案是,在以下浏览器上工作

  1. Google Chrome
  2. Firefox
  3. Microsoft Edge
  4. Safari

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Untitled Document</title>
    </head>
    
    <body>
    <h2>Poly Filler Script for Date/Time</h2>
    <form method="post" action="">
        <input type="date" />
        <br/><br/>
        <input type="time" />
    </form>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="http://cdn.jsdelivr.net/webshim/1.12.4/extras/modernizr-custom.js"></script>
    <script src="http://cdn.jsdelivr.net/webshim/1.12.4/polyfiller.js"></script>
    <script>
      webshims.setOptions('waitReady', false);
      webshims.setOptions('forms-ext', {type: 'date'});
      webshims.setOptions('forms-ext', {type: 'time'});
      webshims.polyfill('forms forms-ext');
    </script>
    
    </body>
    </html>
    
  1. 谷歌浏览器
  2. 火狐
  3. 微软边缘
  4. 苹果浏览器

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Untitled Document</title>
    </head>
    
    <body>
    <h2>Poly Filler Script for Date/Time</h2>
    <form method="post" action="">
        <input type="date" />
        <br/><br/>
        <input type="time" />
    </form>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="http://cdn.jsdelivr.net/webshim/1.12.4/extras/modernizr-custom.js"></script>
    <script src="http://cdn.jsdelivr.net/webshim/1.12.4/polyfiller.js"></script>
    <script>
      webshims.setOptions('waitReady', false);
      webshims.setOptions('forms-ext', {type: 'date'});
      webshims.setOptions('forms-ext', {type: 'time'});
      webshims.polyfill('forms forms-ext');
    </script>
    
    </body>
    </html>
    

回答by Bijan

Two-Script-Include-Solution (2019):

包含两个脚本的解决方案 (2019):

Just include Better-Domand Better-Dateinput-Polyfillin your scripts section.

只需在脚本部分包含Better-DomBetter-Dateinput-Polyfill

Here is a Demo:
http://chemerisuk.github.io/better-dateinput-polyfill/

这是一个演示:http:
//chemerisuk.github.io/better-dateinput-polyfill/

回答by nat

I was having problems with this, maintaining the UK dd/mm/yyyy format, I initially used the answer from adeneo https://stackoverflow.com/a/18021130/243905but that didnt work in safari for me so changed to this, which as far as I can tell works all over - using the jquery-ui datepicker, jquery validation.

我遇到了这个问题,保持英国 dd/mm/yyyy 格式,我最初使用了来自 adeneo https://stackoverflow.com/a/18021130/243905的答案,但这对我来说在 safari 中不起作用,所以改为这样,据我所知,这一切都有效 - 使用 jquery-ui datepicker,jquery 验证。

if ($('[type="date"]').prop('type') !== 'date') {
    //for reloading/displaying the ISO format back into input again
    var val = $('[type="date"]').each(function () {
        var val = $(this).val();
        if (val !== undefined && val.indexOf('-') > 0) {
            var arr = val.split('-');
            $(this).val(arr[2] + '/' + arr[1] + '/' + arr[0]);
        }
    });

    //add in the datepicker
    $('[type="date"]').datepicker(datapickeroptions);

    //stops the invalid date when validated in safari
    jQuery.validator.methods["date"] = function (value, element) {
        var shortDateFormat = "dd/mm/yy";
        var res = true;
        try {
            $.datepicker.parseDate(shortDateFormat, value);
        } catch (error) {
            res = false;
        }
        return res;
    }
}