gpt4 book ai didi

javascript - 如何为元素的所有子元素动态设置样式?

转载 作者:行者123 更新时间:2023-11-29 18:16:20 25 4
gpt4 key购买 nike

我有一个已知的容器 div,我将动态填充子项。我想在子元素上指定一些 .css 属性来定位它们,但我想避免在我创建的每个子元素上手动设置 .css 样式。我将能够为每组元素动态生成一个唯一的类,因此如果有一种方法可以应用影响与特定选择器匹配的元素的所有子元素的 css,我愿意这样做。

我的应用程序执行类似 this fiddle. 的操作

var numChildren = 0;

$('.myButton').on('click', function(){

$('<div class=childDiv' + numChildren + '>Div!</div>')
.appendTo('.myDiv')
.css({
display: 'inline',
'padding-left': (10 + 10*numChildren) + 'px'
//I'd like to put something like this padding left class on the parent div.
//I know the class of all children that should have this style,
//but I don't know until I create the child.
});

$('<div class=childDiv' + numChildren + '>Div!</div>')
.appendTo('.secondDiv')
.css({
display: 'inline',
'padding-left': (10 + 10*numChildren) + 'px'
});

numChildren++;
});

在这个例子中,我动态地生成了几个 child ,他们的类如 childDiv0。我可以使用特定的 padding-left 手动设置它们的样式,但在我的实际应用程序中,我正在生成大量元素,并且快速呈现它们所需的回流正在减慢我的应用程序。有没有办法将 css 应用于 parent 而不是 child ?我可以做类似的事情吗:

$('.parentElement').css(
':childWithSelector(.childDiv'+ numChildren + ').width', //Not a real thing :(
10 + 10*numChildren + 'px'
);

jQuery 是可选的。

最佳答案

在纯 CSS 中,您可以使用您的(唯一)类或 ID 选择直接子代或所有后代

/* color only immediate children red */
.myclass > * {
color: red;
}
/* color all descendants red */
.myclass * {
color: red;
}
/* similar, with an ID */
#myelement > * {
color: red;
}

与这些匹配的 jQuery 简单选择器是

var children = $('> *', $('.myclass'));
var descendants = $('*', $('.myclass'));

您可以在这些上使用 .each()

关于javascript - 如何为元素的所有子元素动态设置样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23021298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com