如何检查一个类是否具有某些符号,如果有,请对其进行一些处理?

时间:2018-12-07 13:21:25

标签: javascript jquery html css

此代码将类用作css属性,并将=之后的所有内容用作其值。

例如:

function getProp(classStr) {
  return classStr.split('=')[0]
}

function getValues(classStr) {
  var values = classStr.split('=')[1]
  return values.split(',').join(' ')
}

function transform(el, prop, values) {
  $(el).css(prop, values)
}


var elements = $('div, p, span, img, li, ul, a, h1, h2, h3, h4, h5, h6')
elements.each(function(i, el) {
  var classList = $(el).attr('class')
  if (!classList) return
  var classProps = classList.split(' ')
  $(classProps).each(function(i, str) {
    var prop = getProp(str)
    var values = getValues(str)
    transform(el, prop, values)
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='color=red font-size=50px font-family=arial'>hello world</div>

soo ..这是个问题。如果您想为一个属性分配多个值,例如border=2px,solid,black,并且在此之前,如果有一个甚至没有=符号的类,整个代码就会崩溃。

我想是因为

function getValues(classStr) {
  var values = classStr.split('=')[1]
  return values.split(',').join(' ')
}

功能?

我们如何检查该属性是否没有值(standart css类)或多个用逗号写的值(border=2px,solid,black)?

3 个答案:

答案 0 :(得分:1)

您可以使用正则表达式获取匹配的参数。注意,我添加了一个名为taco的类,它不会引发结果

这是一个功能齐全的示例,以您的代码为基础

function transformValue(value) {
  if (!value.includes('rgb')) {
    return value.split(',').join(' ');
  }
  return value;
}

function transform(el, prop, values) {
  $(el).css(prop, values);
}


var elements = $('div, p, span, img, li, ul, a, h1, h2, h3, h4, h5, h6');
elements.each(function(i, el) {
  var classList = $(el).attr('class');
  if (!classList) return true;
  
  var regex = /([\w-]+)=([\w\d,%()\.]+)/g;
  var matches;
  var params = [];

  while (matches = regex.exec(classList)) {
    var prop = matches[1];
    var values = transformValue(matches[2]);
    transform(el, matches[1], values);
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='color=red font-size=50px font-family=arial taco border=1px,solid,red margin-left=20% background-color=rgba(0,255,0,0.5)'>hello world</div>

推理和表现

有些人可能会质疑我选择使用正则表达式的原因,因为它因效率低而声誉不佳;但是,鉴于非常规表达途径仅增加了0.75%,我发现解决方案的可读性是一个不错的选择。

https://jsperf.com/so53670448

答案 1 :(得分:1)

对于类名/列表,这是很奇怪的,不是真正有效的语法。无论如何,您不需要jQuery即可将class属性字符串转换为style属性,此外,您的代码可以更简洁。类似于:

setStyle(document.querySelector("div#weird"));
setStyleFromShortcuts(document.querySelector("div#weirder"));

function setStyle(elemWithWeirdClass) {
  const weirdClass = Array.from(elemWithWeirdClass.classList);
  if (weirdClass.length < 1 || !weirdClass.join("").includes("=")) { return; }
  const converted = weirdClass
      .reduce( (styleElement, semiClass) => 
          [...styleElement, semiClass.split("=").join(":")], []).join(";");
  elemWithWeirdClass.removeAttribute("class");
  elemWithWeirdClass.setAttribute("style", converted);
}

function setStyleFromShortcuts(elemWithWeirdClass) {
  const shortCuts = {
    c: "color",
    fs: "font-size",
    ff: "font-face"
  }
  const weirdClass = Array.from(elemWithWeirdClass.classList);
  const getShortCut = ([key, value]) => `${shortCuts[key]}:${value}`;
  if (weirdClass.length < 1 || !weirdClass.join("").includes("=")) { return; }
  const converted = weirdClass
      .reduce( (styleElement, semiClass) => 
          [...styleElement, getShortCut(semiClass.split("="))], []).join(";");
  elemWithWeirdClass.removeAttribute("class");
  elemWithWeirdClass.setAttribute("style", converted);
}
<div id="weird" class='color=red font-size=50px font-family=arial'>hello world</div>

<div id="weirder" class='c=orange fs=50px ff=times new roman'>hello world</div>

答案 2 :(得分:1)

正则表达式比简单的索引要昂贵得多。在功能上,正则表达式让他们可以尝试...

此代码也与您的代码有所不同,一个“ IF” ...

function getProp(classStr) {
  return classStr.split('=')[0]
}

function getValues(classStr) {
  var values = classStr.split('=')[1]
  return values.split(',').join(' ')
}

function transform(el, prop, values) {
  $(el).css(prop, values)
}


var elements = $('div, p, span, img, li, ul, a, h1, h2, h3, h4, h5, h6')
elements.each(function(i, el) {
  var classList = $(el).attr('class')
  if (!classList) return
  var classProps = classList.split(' ')



  $(classProps).each(function(i, str) {

    //if contain a symbol '=' is procesed, like a css
    //else do nothing ...because is a class
    if ( str.indexOf('=') > -1 ) {
        var prop = getProp(str)
        var values = getValues(str)
        transform(el, prop, values)
    }


  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='color=red class-temporal border=1px,solid,red font-size=50px font-family=arial'>hello world</div>