getStyle()样式,setStyle样式

2021-05-02  本文已影响0人  zhao_ran
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;
    }
  }
};
上一篇 下一篇

猜你喜欢

热点阅读