13

第一部分:

我知道有很多东西可以告诉您浏览器是否支持某个 HTML5 属性,例如http://diveintohtml5.info/detect.html,但它们没有告诉您如何从个人那里获取类型元素并使用该信息来初始化您的插件。

所以我尝试了:

alert($("input:date"));
//returns "[object Object]" 

alert($("input[type='date']")); 
//returns "[object Object]"

alert($("input").attr("type"));
//returns "text" ... which is a lie. it should have been "date"

没有那些工作。

我最终想出了这个(确实有效):

var inputAttr = $('<div>').append($(this).clone()).remove().html().toLowerCase();
alert(inputAttr);
// returns "<input min="-365" max="365" type="date">"

谢谢:http: //jquery-howto.blogspot.com/2009/02/how-to-get-full-html-string-including.html

所以我的第一个问题: 1、为什么在不支持html5的浏览器中看不到“type”属性?您可以编造任何其他属性和虚假值并读取它。2. 为什么我的解决方案有效?为什么它是否在 DOM 中很重要?

B部分:

以下是我使用检测器的基本示例:

  <script type="text/javascript" >
    $(function () {
    var tM = document.createElement("input");
    tM.setAttribute("type", "date");
        if (tM.type == "text") {
            alert("No date type support on a browser level. Start adding date, week, month, and time fallbacks");
        //   Thanks: http://diveintohtml5.ep.io/detect.html

            $("input").each(function () {
                // If we read the type attribute directly from the DOM (some browsers) will return unknown attributes as text (like the first detection).  Making a clone allows me to read the input as a clone in a variable.  I don't know why.
                var inputAttr = $('<div>').append($(this).clone()).remove().html().toLowerCase();

                    alert(inputAttr);

                    if ( inputAttr.indexOf( "month" ) !== -1 )

                    {
                        //get HTML5 attributes from element
                        var tMmindate =  $(this).attr('min');
                        var tMmaxdate =  $(this).attr('max');
                        //add datepicker with attributes support and no animation (so we can use -ms-filter gradients for ie)
                         $(this).datepick({ 
                            renderer: $.datepick.weekOfYearRenderer,
                            onShow: $.datepick.monthOnly,
                            minDate: tMmindate, 
                            maxDate: tMmaxdate, 
                            dateFormat: 'yyyy-mm', 
                            showAnim: ''}); 
                    }
                    else
                    {

                        $(this).css('border', '5px solid red');
                        // test for more input types and apply init to them 
                    }

                });         
            }
        });

        </script>

现场示例:http: //joelcrawfordsmith.com/sandbox/html5-type-detection.html

还有一个好处/问题:谁能帮我在我的 HTML5 输入类型修复程序中减少一些脂肪?

我的功能已关闭(向 IE6-IE8 和 FF 添加回退,而无需添加类来初始化)

是否有更有效的方法来遍历神秘输入类型的 DOM?在我的示例中,我应该使用 If Else、函数还是案例?

谢谢大家,

乔尔

4

8 回答 8

26

检测支持的输入类型的一种更好的方法是简单地创建一个输入元素并遍历所有可用的不同输入类型并检查type更改是否有效:

var supported = { date: false, number: false, time: false, month: false, week: false },
    tester = document.createElement('input');

for (var i in supported){
    try {
        tester.type = i;
        if (tester.type === i){
            supported[i] = true;
        }
    } catch (e) {
        // IE raises an exception if you try to set the type to 
        // an invalid value, so we just swallow the error
    }
}

这实际上利用了不支持该特定输入类型的浏览器将回退到使用文本的事实,从而允许您测试它们是否受支持。

然后,您可以使用supported['week'],例如,检查week输入类型的可用性,并通过它进行回退。在这里查看一个简单的演示:http: //www.jsfiddle.net/yijiang/r5Wsa/2/。您也可以考虑使用Modernizr来进行更强大的 HTML5 功能检测。


最后,一个更好的方法outerHTML是,不管你信不信,使用outerHTML. 代替

var inputAttr = $('<div>').append($(this).clone()).remove().html().toLowerCase();

为什么不直接使用:

var inputAttr = this.outerHTML || new XMLSerializer().serializeToString(this);

(是的,如您所见,有一个警告 - outerHTMLFirefox 不支持,所以我们需要一个简单的解决方法,来自这个 Stack Overflow 问题)。


编辑:找到一种方法来测试本机表单 UI 支持,来自此页面: http: //miketaylr.com/code/html5-forms-ui-support.html。以某种方式支持这些类型的 UI 的浏览器也应该防止在这些字段中输入无效值,因此我们在上面所做的测试的逻辑扩展是这样的:

var supported = {date: false, number: false, time: false, month: false, week: false},
    tester = document.createElement('input');

for(var i in supported){
    tester.type = i;
    tester.value = ':(';

    if(tester.type === i && tester.value === ''){
        supported[i] = true;
    }
}

同样,不是 100% 可靠 - 这仅适用于对其值有​​一定限制的类型,而且绝对不是很好,但这是朝着正确方向迈出的一步,现在肯定会解决您的问题。

在此处查看更新的演示:http: //www.jsfiddle.net/yijiang/r5Wsa/3/

于 2010-11-12T02:31:56.967 回答
10

要求 type 属性不适用于所有 Android 库存浏览器。他们假装支持 inputType="date",但他们不提供用于日期输入的 UI(例如日期选择器)。

此功能检测对我有用:

   (function() {
        var el = document.createElement('input'),
            notADateValue = 'not-a-date';
        el.setAttribute('type','date');
        el.setAttribute('value', notADateValue);
        return el.value !== notADateValue;
    })();

诀窍是在日期字段中设置非法值。如果浏览器清理了这个输入,它也可以提供一个日期选择器。

于 2013-10-09T14:14:31.617 回答
3

The type attribute isn't a "made-up" element, it's defined here:

http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.4

...and browsers only "know" about the @type values defined there (unless they are HTML5 aware -- which has defined some new values like "date", "email" etc)

When you query the type attribute some browsers return "text" to you because if a browser doesn't support the "date" type (or anything it doesn't understand) then it falls back to the default value -- which is type="text"

Have you thought of adding a classname (class="date") to the inputs as well then you can just $('.date').each() and then do you detection on that set

于 2010-11-12T00:53:22.303 回答
3

我认为这是 JQuery 中的一个错误! 如果您查看 JQuery 代码本身中的 attr() 函数,JQuery 首先尝试使用括号表示法获取您传入的名称的值。如果它不是未定义的,则返回该值。如果它未定义,则它使用 getAttribute() 方法。

Jquery 对 $("#elem").attr(name) 做了类似的事情:

 if (elem[ name ] !== undefined)
 {
    return elem[name];
 }
 else
 {
    return elem.getAttribute( name )
 }

问题是 Jquery 假设如果 elem[name] 不是未定义的,那么 elem[name] 是正确的。

考虑以下示例:

<input type="date" id="myInput" name="myInput" joel="crawford" />    

var myInput = document.getElementById('myInput');

alert(myInput['type']);//returns text    
alert(myInput.getAttribute('type'));//returns date
alert($("#myInput").attr('type'));//returns text

alert(myInput['joel']);//returns undefined
alert(myInput.getAttribute('joel'));//returns crawford
alert($("#myInput").attr('joel'));//returns crawford

当你传入 .attr("type") 时,myInput['type'] 返回“text”,所以 Jquery 返回“text”。如果你传入 .attr("joel"),myInput['joel'] 返回 undefined,那么 Jquery 使用 getAttribute('joel') 代替它返回“crawford”。

于 2010-11-18T17:50:51.740 回答
0

您无法在不支持此功能的浏览器中获取 type="date"。如果浏览器检测到类型属性,它不理解它会用 type="text" (默认)覆盖它。

解决这个问题的一种方法(使用 jQuery)是简单地添加课程日期。

然后你可以做类似的事情

$('input.date').each(function() {
    var $this = $(this);
    if($this.attr('type') != 'date') $this.datepicker();
});
于 2010-11-12T01:03:34.807 回答
0

这是一个 jQuery 脚本,它检测浏览器是否支持 HTML5date格式,如果支持,它将所有date字段值更改为yyyy-mm-dd格式,并将所有datetime字段值更改为yyyy-mm-dd hh:mm:ss格式。

// From https://stackoverflow.com/a/10199306
// If the browser supports HTML5 input type="date", change all the values from y/m/dddd format to yyyy-mm-dd format, so they appear properly:
function fix_date_inputs() {
    try {
        var input = document.createElement('input');
        input.setAttribute('type','date');

        var notADateValue = 'not-a-date';
        input.setAttribute('value', notADateValue); 

        var r = (input.value !== notADateValue);

        if ( r ) {
            $( 'input' ).each( function() {
                if (
                    $(this).attr( 'type' ).match( /^date/ ) // date or datetime
                ) {
                    var m_d_y = $(this).context.attributes.value.value; // Because $(this).val() does not work (returns '')

                    var d = new Date( m_d_y );

                    var month = '' + (d.getMonth() + 1);
                    var day = '' + d.getDate();
                    var year = d.getFullYear();

                    if (month.length < 2) month = '0' + month;
                    if (day.length < 2) day = '0' + day;

                    var yyyy_mm_dd = [ year, month, day ].join( '-' );

                    // If we're processing a datetime, add the time:
                    if (
                        $(this).attr( 'type' ) == 'datetime'
                    ) {
                        var h = '' + d.getHours();
                        var i = '' + d.getMinutes();
                        var s = '' + d.getSeconds();

                        if (h.length < 2) h = '0' + h;
                        if (i.length < 2) i = '0' + i;
                        if (s.length < 2) s = '0' + s;

                        yyyy_mm_dd += ' ' + [ h, i, s ].join( ':' );
                    }

                    $(this).val( yyyy_mm_dd ); // Here, val() works to set the new value. Go figure.
                }
            });

        }
    } catch( e ) {
        alert( 'Internal error: ' + e.message );
    }
}
于 2017-12-27T07:47:50.200 回答
0

只是tester.type = i;在 IE 中抛出异常。固定版本:

var get_supported_html5_input_types = function() {
    var supported = {
            date: false,
            number: false,
            time: false,
            datetime: false,
            'datetime-local':false,
            month: false,
            week: false
        },
        tester = document.createElement('input');
    for(var i in supported){
        // Do nothing - IE throws, FF/Chrome just ignores
        try { tester.type = i; } catch (err) {}
        if(tester.type === i){
            supported[i] = true;
        }
    }
    return supported;
};

console.log(get_supported_html5_input_types());

永远测试,永远不要盲目复制粘贴!

于 2017-03-06T13:54:35.433 回答
0

好的,我认为此处描述的用于检测浏览器是否支持日期输入类型的方法非常复杂,如果您想要一种更简单的方法,您可以执行以下操作:

/*
 * Instead of body, you could use the closest parent where you know your input is going to be 
 */
$("body").on("focus", "input[type='date']", function(){
    let attribute, property;
    attribute= $(this).attr("type").toUpperCase();
    property= $(this).prop("type").toUpperCase();
    if(attribute!== property){
        console.log("This browser doe not support type='date'");
        //Pop up your own calendar or use a plugin 
    }
});

一旦你用 type="date" 聚焦一个输入,这个函数就会被执行,如果它不存在于页面上也没关系,监听器会一直观察直到 body 上有一个新的 input[type="date"] ,但正如评论中所建议的那样,如果您有一个更接近的容器,并且您知道该容器将始终包含输入,那么您可以更改它而不是使用“body”。

无论如何,JS 侦听器都很快

于 2021-05-07T14:26:18.660 回答