[英]Add CSS subclass with jQuery addclass
我正在嘗試使用jQuery將子類添加到類中,我的CSS如下所示:
.block:nth-child(7) .permahover {
top: 0 !important;
left: 0 !important;
opacity: 0;
filter: alpha(opacity=0);
-webkit-transform: translate(0, 0) !important;
-ms-transform: translate(0, 0) !important;
transform: translate(0, 0) !important
}
這是供參考的js代碼:
$(".block:nth-child(7)").mouseenter(function () {
$(".block:nth-child(7)").addClass("permahover");
});
如果我刪除類名稱中的“ .block:nth-child(7)”,使其看起來像“ .permahover”,那么一切都會進行,但我需要將其作為子類。 我嘗試通過將javascript“ .addClass(” permahover“)”替換為“ .addClass(” block:nth-child(7).permahover“))來嘗試,但正如預期的那樣,它沒有用。有什么辦法可以解決這個問題如果沒有,是否有任何解決方法(即使要求我不要使用jQuery)?
您不能將偽類添加到DOM
元素。 如果您考慮一下,您將理解不可能將:nth-child(7)
類添加到不是其父級的第七個子級的元素中。
但是對於您的問題,您甚至不需要它,您應該刪除.permahover
之前的.permahover
.block:nth-child(7).permahover {
top: 0 !important;
left: 0 !important;
opacity: 0;
filter: alpha(opacity=0);
-webkit-transform: translate(0, 0) !important;
-ms-transform: translate(0, 0) !important;
transform: translate(0, 0) !important
}
如果您在此處留出空間,您的CSS
規則將在第7個.block
內將一個與permahover
類的子元素匹配。
<div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block permahover"></div> <!-- .block:nth-child(7).permahover { ... } -->
</div>
<div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block">
<div class="permahover"></div> <!-- .block:nth-child(7) .permahover { ... } -->
</div>
</div>
並且不要重復jQuery
查詢:
$(".block:nth-child(7)").mouseenter(function () {
$(this).addClass("permahover");
});
或者,如果.permahover
類添加到子元素,則可以執行以下操作:
$(".block:nth-child(7)").mouseenter(function () {
$(" > *", this).addClass("permahover");
});
您的CSS規則指定一個.block
類,該類是第7個子類,該子類具有一個帶有.permahover
類的子元素。 我認為您想要的是:
.block:nth-child(7).permahover { ... }
這指定了同時具有.block
和.permahover
類的元素,該元素是第7個子元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.