美文网首页
getStyle()样式,setStyle样式

getStyle()样式,setStyle样式

作者: zhao_ran | 来源:发表于2021-05-02 21:35 被阅读0次
    function getStyle(obj, name) {//obj:元素对象,name:样式属性名
          if (window.getComputedStyle) {
            return getComputedStyle(obj, null)[name];
          } else {
            return obj.currentStyle[name];
          }
        }
    
    另一种写法
     const SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
        const MOZ_HACK_REGEXP = /^moz([A-Z])/;
    
    
        function getStyle(element, styleName) {
          if (!element || !styleName) return null;
          styleName = camelCase(styleName);
          if (styleName === 'float') {
            styleName = 'cssFloat';
          }
          try {
            var computed = document.defaultView.getComputedStyle(element, '');
            return element.style[styleName] || computed ? computed[styleName] : null;
          } catch (e) {
            return element.style[styleName];
          }
        };
    
        const camelCase = function (name) {
          return name.replace(SPECIAL_CHARS_REGEXP, function (_, separator, letter, offset) {
            return offset ? letter.toUpperCase() : letter;
          }).replace(MOZ_HACK_REGEXP, 'Moz$1');
        };
    
    获取文本的宽度
    //node:元素对象
    const range = document.createRange();
        range.setStart(node, 0);
        range.setEnd(node, node.childNodes.length);
        const rangeWidth = range.getBoundingClientRect().width; // 文本区域宽度
    
    export function setStyle(element, styleName, value) {
      if (!element || !styleName) return;
    
      if (typeof styleName === 'object') {
        for (var prop in styleName) {
          if (styleName.hasOwnProperty(prop)) {
            setStyle(element, prop, styleName[prop]);
          }
        }
      } else {
        styleName = camelCase(styleName);
        if (styleName === 'opacity' && ieVersion < 9) {
          element.style.filter = isNaN(value) ? '' : 'alpha(opacity=' + value * 100 + ')';
        } else {
          element.style[styleName] = value;
        }
      }
    };
    

    相关文章

      网友评论

          本文标题:getStyle()样式,setStyle样式

          本文链接:https://www.haomeiwen.com/subject/vgcxdltx.html