我想将<input type='range' />
HTML5 用于支持它的浏览器并降级为<select />
如果不支持它。我正在使用 Ruby-on-Rails,所以其他一切都失败了,我可以在服务器端做这样的事情。
不过,我更希望有一些更符合通过 Javascript 完成的渐进增强的想法。如果是 JQuery,则加分。
我想将<input type='range' />
HTML5 用于支持它的浏览器并降级为<select />
如果不支持它。我正在使用 Ruby-on-Rails,所以其他一切都失败了,我可以在服务器端做这样的事情。
不过,我更希望有一些更符合通过 Javascript 完成的渐进增强的想法。如果是 JQuery,则加分。
查看Modernizr,它会告诉您是否支持范围。我相信该技术是创建一个范围输入并检查它的类型——如果它仍然是“范围”,那么它是受支持的。否则它应该报告“文本”,这是其他浏览器的后备。
首先检测浏览器是否可以处理 HTML 5,然后使用以下内容:
$('input').each(function (i, item) {
if ($(item).attr('min') !== undefined && $(item).attr('max') !== undefined) {
var select = document.createElement("SELECT");
$(select).attr('name', $(item).attr('name'));
$(select).attr('id', $(item).attr('id'));
$(select).attr('disabled', $(item).attr('disabled'));
var step = 1;
if ($(item).attr('step') !== undefined) {
step = parseFloat($(item).attr('step'));
}
var min = parseFloat($(item).attr('min'));
var max = parseFloat($(item).attr('max'));
var selectedValue = $(item).attr('value');
for (var x = min; x <= max; x = x + step) {
var option = document.createElement("OPTION");
$(option).text(x).val(x);
if (x == selectedValue) { $(option).attr('selected', 'selected'); }
$(select).append(option);
};
$(item).after(select);
$(item).remove();
}
});
由于您不能使用input[type=range]
我不得不采用的$(item).attr('min') && $(item).attr('min')
方法的选择器,因此如果您有其他类型的具有这两个属性的输入控件,这将变得有点奇怪。