This question already has answers here:
Is there a “previous sibling” selector?

(22个答案)


5个月前关闭。




我想进行星级评定,但似乎找不到找到悬停时选择所有先前同级的方法。这样的事情是否存在,还是我必须使用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>

关于javascript - CSS选择所有 previous sibling 姐妹进行星级评定,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/63876804/

10-11 14:22