![](/img/trans.png)
[英]How to select all elements except the ones with a given class, using jQuery?
[英]jQuery: select all elements of a given class on hover, except for this
我在同一個類的頁面上有十個元素。
當我將鼠標懸停在其中一個上面時,我想改變其他九個。
這是我到目前為止所擁有的......
$("*[class='myClass']:not(this)").css({"top":"10px"});
有任何想法嗎?
使用屬性選擇器按類選擇有點多余(更不用說慢),因為有一個類選擇器。 試試這個:
$(".myClass").mouseover(function() {
$('.myClass').not(this).css({"top":"10px"});
});
如果要重置mouseout的效果,請使用帶有兩個函數參數的hover()
。 此外,在這種情況下使用類更好。
$(".myClass").hover(function() {
$('.myClass').not(this).addClass('foo');
},
function() {
$('.myClass').not(this).removeClass('foo');
});
.foo { top: 10px; }
你可以使用這個:
$(".myClass:not(:hover)")
或這個:
$(".myClass").not(":hover")
或這個:
$(".myClass").not(this)
最后一個假定您在mouseover
或mousenter
(或hover
)事件處理程序中。 我也相信你必須在mouseout上重置樣式。 工作證明: http : //jsfiddle.net/tt8cz/
您也可以使用.not
方法,該方法也接受jQuery對象:
$('.myClass').not($(this)).css({"top":"10px"});
文檔乍一看沒有提到這種可能性,但最初的評論之一就是這樣
你也可以用CSS做到這一點:
HTML:
<ol id="items">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ol>
CSS:
#items:hover > li { padding-left:5px; }
#items:hover > li:hover { padding-left:0; }
我使用了padding-left
,但你可以使用任何屬性。
JSFiddle 。
如果我正確理解你要做的事情,你可以改變.myClass
所有元素的.myClass
,然后在this
更改它:
$('.myClass').hover(function() {
$(".myClass").css({"background":"blue"});
$(this).css({"background":"red"});
});
或者也可以像Rory McCrossan所建議的那樣處理懸停狀態。
我使用background-color參數制作了下一個樣本。
$(document).ready(function(e) {
$('.myClass').live('mouseover',function(){
var element = $(this);
$(this).css({"background-color":"#FF0000"});
$('.myClass').each(function(){
if(element.html() != $(this).html()){
$(this).css({"background-color":"#FFFFFF"});
}
});
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.