目标: 成功将变量作为参数传递给nth-child。在下面的示例中,第三行应该变为绿色。
问题: 当前参数被忽略为变量。
问题: 是否可能实现?如果是,我需要改变什么?
示例代码:
:root {
--n: 3;
}
div p:nth-child(var(--n)) {
background: green;
padding: 10px;
}
<div>
<p>a</p>
<p>b</p>
<p>c</p>
</div>
目标: 成功将变量作为参数传递给nth-child。在下面的示例中,第三行应该变为绿色。
问题: 当前参数被忽略为变量。
问题: 是否可能实现?如果是,我需要改变什么?
示例代码:
:root {
--n: 3;
}
div p:nth-child(var(--n)) {
background: green;
padding: 10px;
}
<div>
<p>a</p>
<p>b</p>
<p>c</p>
</div>
:
。这也意味着不幸的是,您不能在选择器或媒体查询中使用这些自定义属性。const dynamicStyles = document.getElementById('dynamicStyles');
const n = getComputedStyle(document.documentElement).getPropertyValue('--n');
dynamicStyles.textContent = `
div p:nth-child(${n}) {
background: green;
padding: 10px;
}
`;
:root {
--n: 3;
}
<style id="dynamicStyles"></style>
<div>
<p>a</p>
<p>b</p>
<p>c</p>
</div>
你不能仅使用CSS来实现这个功能,但是你可以尝试编写一个JS函数来实现。
这个函数:
getComputedStyle(document.documentElement)
.getPropertyValue('--n');
根据你的:root{},将会得到'3'。
现在,由于你不能在CSS中放置JS,所以你必须在HTML文件中完成所有这些操作。因此,你的任务是在使用此函数获取的变量周围包装一个HTML样式标签:
<script>
document.getElementById('custom-container'); //Select the div container
node.innerHTML('<style> #custom-container p:nth-child('); //Wrap style around the variable
getComputedStyle(document.documentElement)
.getPropertyValue('--n'); //get your variable, in this case '3'
node.innerHTML('){background: green;padding: 10px;}</style>'); // Close the wrapping and define the style
</script>
<div id="custom-container"> <!-- Mark your div container with and ID -->
<p>a</p>
<p>b</p>
<p>c</p>
</div>
innerHTML
,顺便提一下,它不是一个函数,而是一个属性。此外,你的代码片段会抛出一个错误 "message": "Script error.",
。 - connexo
document.querySelector(\
div p:nth-child(${n})`).classList.add("bg-green");并且定义一个
bg-green` 类的 CSS 规则。 - Tom