CSSCore

CSSCore用于添加、移除、判断是否包含某个样式类,以及是否某个校验器。

'use strict';

// 首参否值报错
var invariant = require('./invariant');

// 通过父节点判断元素element是否匹配某个选择器selector
function matchesSelector_SLOW(element, selector) {
  var root = element;
  while (root.parentNode) {
    root = root.parentNode;
  }

  var all = root.querySelectorAll(selector);
  return Array.prototype.indexOf.call(all, element) !== -1;
}

var CSSCore = {

  // 添加样式类
  addClass: function addClass(element, className) {
    !!/\s/.test(className) ? 
      process.env.NODE_ENV !== 'production' ? 
        invariant(false, 'CSSCore.addClass takes only a single class name. "%s" contains ' 
          + 'multiple classes.', className) 
        : invariant(false) 
      : void 0;

    if (className) {
      if (element.classList) {
        element.classList.add(className);
      } else if (!CSSCore.hasClass(element, className)) {
        element.className = element.className + ' ' + className;
      }
    }
    return element;
  },

  // 移除样式类
  removeClass: function removeClass(element, className) {
    !!/\s/.test(className) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'CSSCore.removeClass takes only a single class name. "%s" contains ' + 'multiple classes.', className) : invariant(false) : void 0;

    if (className) {
      if (element.classList) {
        element.classList.remove(className);
      } else if (CSSCore.hasClass(element, className)) {
        element.className = element.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)', 'g'), '$1').replace(/\s+/g, ' ') // multiple spaces to one
        .replace(/^\s*|\s*$/g, ''); // trim the ends
      }
    }
    return element;
  },

  // 按第三个参数布尔值添加或移除样式类
  conditionClass: function conditionClass(element, className, bool) {
    return (bool ? CSSCore.addClass : CSSCore.removeClass)(element, className);
  },

  // 判断元素是否包含某个样式类
  hasClass: function hasClass(element, className) {
    !!/\s/.test(className) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'CSS.hasClass takes only a single class name.') : invariant(false) : void 0;
    if (element.classList) {
      return !!className && element.classList.contains(className);
    }
    return (' ' + element.className + ' ').indexOf(' ' + className + ' ') > -1;
  },

  // 判断元素是否匹配某个选择器
  matchesSelector: function matchesSelector(element, selector) {
    var matchesImpl = element.matches || element.webkitMatchesSelector || element.mozMatchesSelector || element.msMatchesSelector || function (s) {
      return matchesSelector_SLOW(element, s);
    };
    return matchesImpl.call(element, selector);
  }

};

module.exports = CSSCore;

相关推荐