You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检测浏览器是否支持HTML属性值?以input的week/month类型为例

检测input的week/month类型支持并实现date回退方案

一、检测浏览器是否支持指定input type

可以通过创建临时input元素,设置目标type后检查实际渲染的type值来判断支持性——不支持的type会被浏览器自动降级为text,因此对比设置前后的type即可得出结果:

function isInputTypeSupported(type) {
  const testInput = document.createElement('input');
  testInput.type = type;
  return testInput.type === type;
}

// 检测week和month的支持情况
const supportsWeekInput = isInputTypeSupported('week');
const supportsMonthInput = isInputTypeSupported('month');

二、实现向date类型的回退

如果浏览器不支持week或month类型,遍历页面中对应类型的input,将其type替换为date即可。如果input有预设值,还需要做格式转换(因为week/month的value格式和date不兼容):

// 处理week类型回退
if (!supportsWeekInput) {
  document.querySelectorAll('input[type="week"]').forEach(input => {
    input.type = 'date';
    // 可选:将YYYY-Www格式的week值转换为对应周的周一
    if (input.value) {
      const [year, weekNum] = input.value.split('-W');
      const firstDayOfYear = new Date(year, 0, 1);
      const mondayOfWeek = new Date(firstDayOfYear.setDate(firstDayOfYear.getDate() + (weekNum - 1)*7 - firstDayOfYear.getDay() + 1));
      input.value = mondayOfWeek.toISOString().split('T')[0];
    }
  });
}

// 处理month类型回退
if (!supportsMonthInput) {
  document.querySelectorAll('input[type="month"]').forEach(input => {
    input.type = 'date';
    // 可选:将YYYY-MM格式的month值转换为该月第一天
    if (input.value) {
      input.value = `${input.value}-01`;
    }
  });
}

说明

  • 该代码要在DOM加载完成后执行,或者放在页面底部,确保能选中目标input元素。
  • 格式转换逻辑可根据业务需求调整(比如week可以转换为周日而非周一)。

内容的提问来源于stack exchange,提问作者Claudio Bonifazi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 21:45:33