繁体   English   中英

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 class classA为目标元素,并且 CSS 特异性为 0、0、1、0。假设 10。

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

为什么这个奇怪的词对你来说很重要?

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

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

以下选择器

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

具有特异性20 ,并将覆盖来自具有较低特异性的选择器的相同 CSS 属性。 因此,您甚至 animation 的工作原理是覆盖.box{transform: translateX(4000%);}

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

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

在此处阅读有关带有插图的特异性的更多信息: specifics-on-css-specificity

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM