HTML5类型检测和插件初始化 [英] HTML5 Type Detection and Plugin Initialization

查看:98
本文介绍了HTML5类型检测和插件初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

浏览器支持某个HTML5属性,例如 http://diveintohtml5.info/detect.html ,但他们没有告诉你如何从单个元素中获取类型并使用该信息来初始化你的插件。



所以我试过:

  alert($(输入:日期)); 
//返回[object Object]

alert($(input [type ='date']));
//返回[object Object]

alert($(input)。attr(type));
//返回文本......这是一个谎言。应该是日期

没有人工作过。



我最终想出了这个(可行):

  var inputAttr = $('< div> ;')追加($(本).clone()),删除()HTML()toLowerCase()。; 
alert(inputAttr);
//返回< input min = - 365max =365type =date>

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



所以我的第一个问题:
1.为什么我不读在不支持html5的浏览器中输入属性?您可以组成任何其他属性和虚假值并阅读它。
2.为什么我的解决方案有效?为什么它在DOM中不重要?



B部分:

下面是我使用探测器的基本示例:

 < script type =text / javascript > 
$(function(){
var tM = document.createElement(input);
tM.setAttribute(type,date);
if(tM .type ==text){
alert(在浏览器级别没有日期类型支持,开始添加日期,星期,月份和时间回退);
// Thanks:http:/ /diveintohtml5.ep.io/detect.html

$(input)。each(function(){
//如果我们直接从DOM读取类型属性(某些浏览器)将返回未知属性作为文本(如第一次检测)。制作克隆允许我将输入读作变量中的克隆。我不知道为什么。
var inputAttr = $('< div> ();')。append($(this).clone())。remove()。html()。toLowerCase();
$ b $ alert(inputAttr);

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

{
//从元素
获取HTML5属性var tMmindate = $(this).attr('min');
var tMmaxdate = $(this).attr('max');
//添加带有属性支持并且没有动画的datepicker(因此我们可以使用-ms-filter渐变来实现)
$(this).datepick({
renderer:$ .datepick.weekOfYearRenderer ,
onShow:$ .datepick.monthOnly,
minDate:tMmindate,
maxDate:tMmaxdate,
dateFormat:'yyyy-mm',
showAnim:''} );
}
else
{

$(this).css('border','5px solid red');
//测试更多输入类型并将init应用于它们
}

});
}
});

< / script>

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



还有一个青睐/问题:
任何人都可以帮我在HTML5输入法修复器中减少一些脂肪吗?



我的功能有所下降(为IE6-IE8增加了回退,而FF没有向init添加类)



是否有更有效的方法来迭代DOM以获取神秘输入类型?
如果我在我的例子中使用If Else,或函数或案例?



全部谢谢,



Joel

解决方案

首先,停止使用 alert 来完成你的调试!取一份Firebug和FireQuery,并用 console.log()代替。即使你使用 alert(),你也应该使用 $(input [type ='date'])。length 查找选择器是否返回任何内容 - object [object] 并没有告诉你这里有什么用处。






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

  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会引发异常,所以我们只是吞下错误
}
}

这实际上利用了浏览器没有的事实支持特定输入类型将回退到使用文本,从而允许您测试它们是否受支持。例如,您可以使用支持的['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); 

(是的,你可以看到,有一个警告 - outerHTML < Firefox不支持/ code>,因此我们需要一个简单的解决方法,来自这个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 /


PART A:

I know there are a lot of things out there that tell you if a browser supports a certain HTML5 attribute, for example http://diveintohtml5.info/detect.html, but they don't tell you how to acquire the type from individual elements and use that info to init your plugins.

So I tried:

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"

None those worked.

I eventually came up with this (that does work):

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

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

So my first question: 1. Why can I not read the "type" attribute in browsers that don't support html5? You can make up any other attribute and bogus value and read it. 2. Why does my solution work? Why does it matter if its in the DOM or not?

PART B:

Below is a basic example of what I am using the detector for:

  <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>

Live example: http://joelcrawfordsmith.com/sandbox/html5-type-detection.html

And a favor/question: Can anyone help me cut some fat in my HTML5 input type fixer?

I have the functionality down (adds fallbacks to IE6-IE8, and FF with out adding classes to init off of)

Are there are more efficient methods for iterating over the DOM for mystery input types? And should I be using an If Else, or a function, or a case in my example?

Thanks All,

Joel

解决方案

First of all, stop using alert to do your debugging! Grab a copy of Firebug and FireQuery and use those with console.log() instead. Even if you're working with alert(), you really should be using $("input[type='date']").length to find the if the selector returned anything - object [object] isn't telling you anything useful here.


A far superior method for detecting supported input types is to simply create an input element and loop through all of the different input types available and check if the type change sticks:

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
    }
}

This actually makes use of the fact that browsers which do not support that particular input type will fall back to using text, thereby allowing you to test if they're supported or not.

You can then use supported['week'], for instance, to check for the availability of the week input type, and do your fallbacks through this. See a simple demo of this here: http://www.jsfiddle.net/yijiang/r5Wsa/2/. You might also consider using Modernizr for more robust HTML5 feature detection.


And finally, a better way to get outerHTML is to, believe it or not, use outerHTML. Instead of

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

Why not just use:

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

(Yes, as you can see, there is a caveat - outerHTML isn't supported by Firefox, so we're going to need a simple workaround, from this Stack Overflow question).


Edit: Found a method to do testing for native form UI support, from this page: http://miketaylr.com/code/html5-forms-ui-support.html. Browsers that support the UI for these types in some way should also prevent invalid values from been entered into these fields, so the logical extension to the test we're doing above would be this:

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;
    }
}

Again, not 100% reliable - this is only good for types that have certain restrictions on their values, and definitely not very good, but it's a step in the right direction, and certainly would solve your problem now.

See the updated demo here: http://www.jsfiddle.net/yijiang/r5Wsa/3/

这篇关于HTML5类型检测和插件初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆