本文介绍了CSS选择所有以前的兄弟姐妹进行星级评定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想进行星级评定,但似乎找不到找到悬停时选择所有先前同级的方法。
I want to do a star rating control but I can't seem to find a way to select all previous siblings on hover. Does such thing even exist or do I have to use javascript?
span {
display:inline-block;
width: 32px;
height: 32px;
background-color:#eee;
}
span:hover {
background-color:red;
}
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
推荐答案
// obtain all spans from DOM
const spans = document.querySelectorAll('span');
// set a variable at global scope as indicator
let flag = false;
// add event listener to each span
spans.forEach((sp, j)=>{
sp.addEventListener('click', ()=>{
// if clicked, then not dismissing the background colour after mouse leave
flag = true;
// reassign all spans back to original grey
spans.forEach(dsp=>{
dsp.style.backgroundColor = '#eee';
});
// assign bg to red of the spans from 0 to clicked index
Array.from(new Array(j+1), (x, i) => i).forEach(ind=>{
spans[ind].style.backgroundColor = 'red';
});
});
// redo if mouse enters
sp.addEventListener('mouseenter', ()=>{
flag = false;
});
// if any span is hovered
sp.addEventListener('mouseover', ()=>{
// reassign all spans back to original grey
spans.forEach(dsp=>{
dsp.style.backgroundColor = '#eee';
});
// assign bg to red of the spans from 0 to clicked index
Array.from(new Array(j+1), (x, i) => i).forEach(ind=>{
spans[ind].style.backgroundColor = 'red';
});
});
// in moseleave, only save the background colour if click happened
sp.addEventListener('mouseleave', ()=>{
if(!flag){
spans.forEach(dsp=>{
dsp.style.backgroundColor = '#eee';
});
}
});
});
span {
display:inline-block;
width: 32px;
height: 32px;
background-color:#eee;
}
span:hover {
background-color:red;
opacity: 0.8;
cursor: pointer;
}
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
这篇关于CSS选择所有以前的兄弟姐妹进行星级评定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!