gpt4 book ai didi

javascript - 遍历元素时在数组中向前移动

转载 作者:行者123 更新时间:2023-11-30 11:30:15 25 4
gpt4 key购买 nike

我在页面上有重复元素(部分)。我想在数组中保存的三种颜色之间迭代元素的背景颜色。在其中一些元素中,我有文本 (p),我想遍历这些相同的颜色,但我希望它成为数组中的下一个颜色作为背景。

因此,如果我有一个类似于 ["111111", "222222", "333333"] 的数组,我希望第一部分的背景颜色为#111111,第一个 p 的颜色为#222222 .此外,页面上的元素多于数组中的项目,因此我们需要循环遍历数组。完成后的页面应如下所示:

<body>
<section style="background-color: #111111;">
<p style="color: #222222;">foo bar</p>
</section>
<section" style="background-color: #222222;">
<p style="color: #333333;">foo bar</p>
</section>
<section style="background-color: #333333;">
<!--no p in this one-->
</section>
<section style="background-color: #111111;">
<p style="color: #222222;">foo bar</p>
</section>
</body>

我已经完成了背景色部分,但我不知道如何切换到数组中的下一项并在必要时从第一项重新开始。

var bgColors = ["111111", "222222", "333333"];
$('section').each(function(i) {
var bgColor = bgColors[i % bgColors.length];
$(this).css('background-color', '#'+bgColor);
// How to do text color???
$(this).find("p").css('color', ???);
});

脚本应该是灵活的,以便您可以添加和更改颜色。谢谢。

编辑:我意识到我遗漏了一个重要的点,即并非每个部分都有一个 p,因此您不能单独遍历它们。同样由于 c&p 事故,我的 html 与我的 JS 不匹配。抱歉。

最佳答案

只需使用i+1作为前景的模

这和你申请bgColor的逻辑是一样的,你只需要为前景多一个

var bgColors = ["red", "green", "blue", "yellow"];
$(function() {
$('.section').each(function(i) {
var bgColor = bgColors[i % bgColors.length];
var fgColor = bgColors[(i + 1) % bgColors.length];
$(this).css('background-color', bgColor);
$(this).find(".text").css('color', fgColor);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="section">
<div class="text">foo bar</div>
</div>
<div class="section">
<div class="text">foo bar</div>
</div>
<div class="section">
<div class="text">foo bar</div>
</div>
<div class="section">
<div class="text">foo bar</div>
</div>

关于javascript - 遍历元素时在数组中向前移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46507243/

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