开发者社区> 问答> 正文

IE 9 DOM 元素的 style.setProperty() 参数无效 Bug - IE报错

IE 9 DOM 元素的 style.setProperty() 参数无效 Bug

展开
收起
montos 2020-05-31 08:56:32 681 0
1 条回答
写回答
取消 提交回答
  • "

    呃…… 自己傻逼了…… 实际调用时没完全按文档来……<img src=""http://www.oschina.net/js/ke/plugins/emoticons/images/43.gif"" alt="""" /><img src=""http://www.oschina.net/js/ke/plugins/emoticons/images/17.gif"" alt="""" /><img src=""http://www.oschina.net/js/ke/plugins/emoticons/images/10.gif"" alt="""" /><img src=""http://www.oschina.net/js/ke/plugins/emoticons/images/36.gif"" alt="""" /><img src=""http://www.oschina.net/js/ke/plugins/emoticons/images/38.gif"" alt="""" />

    因为在我的动画方法中为了让数值型 CSS 属性之间的运算更方便,自己写的 Get_Style() 函数会对其返回值自动转类型。当各种计算之后要 Set_Style() 时,setProperty() 的第二个参数可能传入的是 Number 值,而非 IE 9 文档规定的 String……

    其实 W3C 的文档也是这么规定的,但大多数浏览器 都会像“连字符 转 驼峰法”那样隐式转换 CSS 属性值的类型,唯独 IE 9 - CSSStyleDeclaration 的程序猿较了个真儿……

    ——————————————————————

    发个修改后的代码 纪念一下重新开始努力的 IE ——

    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;
    
    function Get_Style(iElement, iName) {
        var iStyle = (IE_Version < 9) ?
                iElement.currentStyle.getAttribute(iName) :
                DOM.defaultView.getComputedStyle(iElement, null).getPropertyValue(iName);
    
        if (typeof iStyle == 'number')
            return iStyle;
    
        var iNumber = iStyle.match(/(\d+(\.\d+)?)(px$)?/i);
        iNumber = iNumber ? Number(iNumber[1]) : NaN;
    
        return  isNaN(iNumber) ? iStyle : iNumber;
    }
    
    var 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,
            (IE_Version != 9) ? iValue : iValue.toString(),
            'important'
        );
    }
    "
    2020-05-31 13:03:41
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载