簡體   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