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之后用rgb值替换randomColor,它将更改颜色,但是随机值不起作用。预先感谢!
答案 0 :(得分:0)
您需要分配颜色而不是随机索引,为此,请使用随机生成的索引(例如:)从数组中调用该项:
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>