我正在尝试解决星级问题。当悬停在任何一颗星星上时,这颗星星应该被分配到黄金级,这样的级应该分配给左侧之前的所有星星。
"use strict";
const starsContainer = document.querySelector('.stars_container');
const stars = document.querySelectorAll('.fas');
starsContainer.addEventListener('mouseover', e => {
let item = e.target;
if (item.classList.contains('fas')) {
Array.from(stars).forEach((el, index, arr) => {
item.classList.add('golden');
item = item.previousElementSibling;
});
}
});
i {
font-size: 50px;
}
.golden {
color: gold;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" rel="stylesheet" />
<div class="stars_container">
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
</div>
当我们将鼠标从星星上移开时,所有提供的黄金级都应该被删除。
我写了一些东西,但我得到一个错误:
Error {
"message": "Uncaught TypeError: Cannot read properties of null (reading 'classList')",
"filename": "https://stacksnippets.net/js",
"lineno": 35,
"colno": 12
}
在控制台中:
Uncaught TypeError: Cannot read properties of null (reading 'classList')
at Array.forEach (<anonymous>)
at HTMLDivElement.<anonymous
请喜欢并支持我的版本)
您不必使用 JS。CSS 有一个选择器
~
,允许您选择在指定元素之后处于相同嵌套级别的相邻元素。要使其工作,您需要更改星号的顺序。这将帮助我们flex
: