zoukankan      html  css  js  c++  java
  • getStyle的实现

    问题:
    获取元素的真实的样式。在DHTML中经常需要操作css属性,但是取值不是很方便。因为直接元素.style.属性的方式取到的是元素的style属性的值,不能得到<style>元素内的值。 

    方法:
    1基本情况

    .1 在HTML种有三种方式定义样式。分别是link外部导入,style元素,元素的style属性
      在DOM2 Styles中提供了一套以上的API
      访问Style属性,必须使用驼峰法的方式

    .2   获取真实style的值
      IE下使用currentStyle。ff下使用getComputedStyle。这两种方式可以取到样式定义的三种方式混合后的最终结果。

    .3   直接获取和设定整个style的值。
      1使用getAttribute("style")或者.style返回。
       这种情况下。ie6/7返回object。ff在getAttribute时返回style的值,在.style时返回[cssStyleDeclaration]
      2使用style.cssText
       对于style="border:1px solid".这种情况下,ff返回原始值。ie返回border-top,borde-left,border-right,border-bottom


    2一些库的具体实现

    1:下面看moo中的getStyle实现

    getComputedStyle: function(property){
    if (this.currentStyle) return this.currentStyle[property.camelCase()];
    var defaultView = Element.getDocument(this).defaultView,
    computed
    = defaultView ? defaultView.getComputedStyle(this, null) : null;
    return (computed) ? computed.getPropertyValue((property == floatName) ? 'float' : property.hyphenate()) : null;
    },

    2:这里是百度tangram的实现和moo相似

    baidu.dom.getComputedStyle = function(element, key){
    element
    = baidu.dom._g(element);
    var doc = baidu.dom.getDocument(element),
    styles;
    if (doc.defaultView && doc.defaultView.getComputedStyle) {
    styles
    = doc.defaultView.getComputedStyle(element, null);
    if (styles) {
    return styles[key] || styles.getPropertyValue(key);
    }
    }
    return '';
    };

    这里的以上getDocument的实现

    getDocument: function(){
    return this.ownerDocument;
    },


    关于defaultView的兼容性

    3自己的总结

    getStyle:function(value){
    if(this.currentStyle)return this.currentStyle[value];
    return this.ownerDocument.defaultView.getComputedStyle(this, null).getPropertyValue(value)
    }


  • 相关阅读:
    Vue和React组件diff更新影响范围对比
    ES6中import和CommonJS中require的区别
    MutationObserver监听DOM变化
    Mint UI中文官网
    为什么在浏览器不支持H265视频播放
    Google谷歌官网首页涂鸦记录
    windows键盘输入无效,键盘灯亮,打字不出字
    javascript实现跨域的方法汇总
    javascript中setInterval的用法
    浅谈Javascript数组的使用
  • 原文地址:https://www.cnblogs.com/lunalord/p/2081717.html
Copyright © 2011-2022 走看看