gpt4 book ai didi

javascript - 数组中的随机项仅返回索引位置,而不是实际值

转载 作者:行者123 更新时间:2023-11-28 00:54:55 25 4
gpt4 key购买 nike

var borderColors = ["rgb(244, 66, 215)", "rgb(119, 0, 247)", "rgb(0, 65, 247)", "rgb(0, 209, 247)", "rgb(0, 247, 86)", "rgb(205, 247, 0)","rgb(247, 90, 0)"]

var borders = document.querySelectorAll(".borders")

for (var i = 0; i < borders.length; i++) {
borders[i].addEventListener("mouseover", function() {
var randomColor = [Math.floor(Math.random() * borderColors.length)]
console.log(randomColor)
this.style.borderColor = randomColor
})
}

randomColor 作为数组索引位置返回,但不是数组项的实际值。如果我在 this.style.borderColor 之后将 randomColor 替换为 rgb 值,它将更改颜色,但随机值不起作用。提前致谢!

最佳答案

您需要分配颜色而不是随机索引,为此使用随机生成的索引调用数组中的元素,例如:

this.style.borderColor = borderColors[randomColor];

var borderColors = ["rgb(244, 66, 215)", "rgb(119, 0, 247)", "rgb(0, 65, 247)", "rgb(0, 209, 247)", "rgb(0, 247, 86)", "rgb(205, 247, 0)", "rgb(247, 90, 0)"]

var borders = document.querySelectorAll(".borders")

for (var i = 0; i < borders.length; i++) {
borders[i].addEventListener("mouseover", function() {
var randomColor = [Math.floor(Math.random() * borderColors.length)];
this.style.borderColor = borderColors[randomColor];
})
}
div.borders {
height: 45px;
text-align: center;
line-height: 43px;
border: 1px solid #000;
}
<div class="borders">Hover me</div>
<br>
<div class="borders">Hover me</div>
<br>
<div class="borders">Hover me</div>

关于javascript - 数组中的随机项仅返回索引位置,而不是实际值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52990154/

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