18910140161

JavaScript-尝试创建一个返回选定CSS属性但相当滞后的函数-堆栈溢出

顺晟科技

2022-10-18 12:46:27

178

我正在尝试创建一个函数,为您提供所需元素的选定CSS属性。但如果在控制台中使用,它会非常滞后,因为它需要获取并匹配所有CSS属性。

function styleOf(elementUseSelectors, propertiesToCheck, tellInConsole) {
  var element = elementUseSelectors;
  var Arguments = propertiesToCheck;
  var calculatedProperties = [];
  var matchedProperties = [];
  if (tellInConsole !== undefined && tellInConsole == true) {
    console.warn("Running styleOf() Please Don't Do Other Calculations This Function Disables Console.")
  }
  for (var i = 0; i < Object.keys(getComputedStyle(element)).length; i++) {
    var value = getComputedStyle(element).getPropertyValue(Object.entries(getComputedStyle(element))[i][0].replace(/([A-Z])/g, ' $1').trim().replaceAll(" ", "-").toLowerCase());
    if (value !== "") {
      calculatedProperties.push(Object.entries(getComputedStyle(element))[i][0].replace(/([A-Z])/g, ' $1').trim().replaceAll(" ", "-").toLowerCase() + ": " + value);
    }
  }
  for (var i = 0; i < calculatedProperties.length; i++) {
    for (var a = 0; a < Arguments.length; a++) {
      if (calculatedProperties[i].includes(Arguments[a])) {
        window.splitted = calculatedProperties[i].split("");
        window.joinThis = [];
        for (var k = 0; k < splitted.indexOf(":"); k++) {
          joinThis.push(splitted[k]);
        };
        if (joinThis.join("") == Arguments[a]) {
          matchedProperties.push(calculatedProperties[i]);
        }
      }
    }
  }
  if (tellInConsole !== undefined && tellInConsole == true) {
    console.warn("StyleOf() Calculations Completed You Can Now Use Console.")
  }
  return matchedProperties
}

顺晟科技:

Welp@kaiido回答了这个问题。
function styleOf(element, properties) { 
const computed = getComputedStyle(element); 
return properties.map( key => key + ": "  +  computed[ key ] )};

var style = styleOf(document.getElementsByTagName("body")[0], ["height", "width", "background-color", "font-size", "color", "font-family"]);

console.log(style);

TreeWalker对象旨在快速解析文档中的DOM节点。如果您展开上面MDN Web文档中给出的示例,您可以输出给定节点的计算CSS属性。

该方法的

第一个属性是要遍历的节点—在本例中是document.body

var treeWalker = document.createTreeWalker(
  document.body,
  NodeFilter.SHOW_ELEMENT,
  { acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } },
  false
);

var nodeList = [];
var currentNode = treeWalker.currentNode;

while(currentNode) {
  nodeList.push(currentNode);
  const style = getComputedStyle(currentNode)
  console.log(style)
  currentNode = treeWalker.nextNode();
  console.log("moving to next node...");
}
  • TAG:
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航