我如何抽象这个 CSS-style-changing 函数

How can I abstract this CSS-style-changing function

我正在尝试抽象一个函数。

此函数遍历给定 DOM 元素(作为参数传递到函数中)的每个子节点,并对每个子节点应用相同的 CSS 样式 属性 & 值.

例如

function styleChildNodes(parent){

const children = parent.childNodes


for (let i = 0; i < children.length; i++) {

const child = children[i];




child.style.background = "red"


} }

在此示例中,我将 CSS 属性: background 及其值硬编码为:"red"。该函数将遍历给定父元素的每个子节点,并将它们的 CSS 背景属性更改为红色。

但是函数内部没有任何硬编码的 CSS 属性-值对,例如:

背景 = "红色" ,或者,能见度 = "hidden"opacity = "1"

我想传入所需的 CSS 属性 及其值作为参数。

这是概念的说明:

function styleChildNodes(parent, property, value){

const children = parent.childNodes



for (let i = 0; i < children.length; i++) {

const child = children[i];




child.style.property = value


} }

CSS 属性 及其值可以是我选择的任何值,我可以像这样使用函数:

styleChildNodes(div, opacity, "0")

styleChildNodes(table, visibility, "hidden")

styleChildNodes(tr, background, "red")

styleChildNodes(div, height, "10px")

这些只是伪代码示例 - 但希望它传达了我正在努力实现的目标。

欢迎任何想法、解决方法或非 eval() 解决方案!

感谢您的阅读:-)

P.S。当我说“我正在尝试抽象一个函数”时,我希望我没有误用“抽象”。如果我使用的术语不精确,请告诉我!

“抽象是一个计算机科学概念,其中实现与其接口分离。”

您可以将 属性 括在括号中,但 属性 需要作为字符串传递,因此请将其括在引号中。

function styleChildNodes(parent, property, value) {
  const children = parent.childNodes
  for (let i = 0; i < children.length; i++) {
    const child = children[i];
    child.style[property] = value
  }
}

你也可以传递一个对象来做多个:

function styleChildNodes(parent, styles) {
  const children = parent.childNodes
  for (let i = 0; i < children.length; i++) {
    const child = children[i];
    child.style[property] = value
    for(style in styles){
        child.style[style] = styles[style]
   }
  }
}

styleChildNodes(parent, {
"color": "red",
"background-color": "green"
}) 

我阅读了样式表,我在名为 .yourClass 的 class 中使用外部属性创建了一个规则,并将此规则添加到样式表中。在我将这个 class 添加到每个节点子节点之后(我的代码中还有深节点子节点)。我创建了一个可能的调用和使用这个函数。有不明白的请追问。

let sheet = document.styleSheets[0]

function styleChildNodes(parent,...cssPropertiesValues){

let formattedCssPropertiesValues = cssPropertiesValues.map((item,index)=>
  index%2 ? `${item};` : `${item}: ` 
 );
 
let rule = `.yourClass { ${formattedCssPropertiesValues.join('')} }` //join convert from array to string. I'm using as separator the empty string to merge the items of the array

sheet.insertRule(rule,0); //the first parameter is a string (its format is `selector{prop1:val1;prop2:val2}`) that represents your rule. The second parameter is the position in the stylesheet where you insert the rule
console.log(rule)
const children = parent.querySelectorAll("*");

//When you have an iterable object like an array or an HTMLCollection
//you can iterate it whit a for of. `child` will be the current item
for (let child of children)
  child.classList.add('yourClass');

}

let parentNode = document.getElementById('my-parent');
styleChildNodes(parentNode,'opacity',0.5,'display','block');
<link rel="stylesheet">

<div id="my-parent">
<span></span>
<p></p>
</div>