【开源中国 APP 全新上线】“动弹” 回归、集成大模型对话、畅读技术报告”
我自己在写 DOM/CSS 动画时,为了规避 CSS 属性名到 JS 属性名的驼峰命名法转换、cssText 正则替换时所带来的代码繁琐、性能损失,用原生 JavaScript 写的 Set_Style() 函数使用 CSSStyleDeclaration.protostyle.setProperty(name, value, priority) 方法来设置 DOM 元素的 style 属性。代码如下 ——
var is_Trident = navigator.userAgent.match(/MSIE (\d+)|Trident[^\)]+rv:(\d+)/i); var IE_Version = is_Trident ? Number(is_Trident[1] || is_Trident[2]) : NaN, PX_Needed = { width: true, 'min-width': true, 'max-width': true, height: true, 'min-height': true, 'max-height': true, 'border-radius': true, margin: true, padding: true, top: true, left: true }; function Set_Style(iElement, iName, iValue) { if ((! isNaN( Number(iValue) )) && PX_Needed[iName]) iValue += 'px'; iElement.style[ (IE_Version < 9) ? 'setAttribute' : 'setProperty' ](iName, iValue, 'important'); }
IE 8、10、11 还有 Firefox、Chrome 一切正常,唯独 IE 9 报错 —— 参数无效(无论第三个参数是 null、空字符串 还是 important)……
【参考文档】
- 微软官方 IE API 文档 —— https://msdn.microsoft.com/en-us/library/ie/ff975226%28v=vs.85%29.aspx
- 第三方兼容 API 文档 —— http://help.dottoro.com/ljdpsdnb.php