第一部分:
我知道有很多东西可以告诉您浏览器是否支持某个 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、函数还是案例?
谢谢大家,
乔尔