在 CSS 中添加 .classA 和 .classB.classA 有什么区别?

What is the difference between adding .classA and .classB.classA in CSS?

问题是当我在 CSS 中输入 .show 而不是 .box.show 偶数框不是来自左侧。 我只想知道为什么?因为我认为它们是同一回事。 但在这段代码中,它们的行为似乎有所不同。

const boxes = document.querySelectorAll('.box');

window.addEventListener('scroll',()=>{
    const triggerPoint=window.innerHeight*4/5;
    boxes.forEach((box)=>{
        const boxTop=box.getBoundingClientRect().top;
        if(boxTop<triggerPoint){
            box.classList.add('show')
        }else{
            box.classList.remove('show')
        }
    })
})
*{
    padding:0;
    margin:0;
    box-sizing: border-box;
}


body{
    background-color: #efedd6;
    min-height: 100%;
    width:100%;
    display:flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    overflow-x: hidden;
}

.box{
    width: 100px;
    height: 100px;
    background-color: rgb(226, 43, 43);
    margin:10px;
    transform: translateX(4000%);
    transition:0.4s;
}

h1{
    margin:10px;
}



.box:nth-of-type(even){
    transform: translateX(-4000%);
}
.box.show{
    transform: translateX(0%);
    transition: .4s;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Scroll Animation</title>
</head>
<body>
    <!-- <h1>scroll to see the Animation</h1> -->
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>


    <script src="main.js"></script>
</body>
</html>

这就是选择器特异性的工作原理 (https://www.w3.org/TR/selectors-3/#specificity)

如果您在开发人员工具中查看 .show 元素,您会看到 transform 样式被 .box:nth-of-type(even) class 覆盖,因为伪 class :nth-of-type具有更高的特异性。

您可以在https://isellsoap.github.io/specificity-visualizer/

查看

.classA 以 CSS classclassA 为目标元素,并且 CSS 特异性为 0、0、1、0。比方说 10。

classA.classB(或.classB.classA)以同时具有class和classAclassB的元素为目标。这次的特异性为 20(两个 classes)。

为什么这个奇怪的词对你的情况很重要?

具有以下默认转换值的选择器的特异性为 10:

.box{
  transform: translateX(4000%);
}

下面的选择器

.box:nth-of-type(even){
   transform: translateX(-4000%);
}

具有 20 的特异性,并且将覆盖具有较低特异性的选择器的相同 CSS 属性。所以你的偶数动画通过覆盖 .box{transform: translateX(4000%);}.

来工作

但是.show{ transform: translateX(0%); }没有更高的特异性,所以它可能无法覆盖原始值。

.box.show{transform: translateX(0%);} 但是,具有 20 的特异性,并且肯定会覆盖原始值,就像偶数元素的选择器一样。

在此处详细了解带有插图的特异性:specifics-on-css-specificity