2011-12-26 87 views
3

HTML:jQuery的:添加類以元素的子

<div class="cell-container"> 
    <img src="image.png" class="thumbnail" /> 
</div> 

CSS:

.hover { 
    background-color: silver; 
} 
.hover-image { 
    border: 1px solid #000; 
} 

的jQuery:

$(".cell-container").mouseover(function() { 
    $(this).addClass("hover"); 
}); 

$(".cell-container").mouseout(function() { 
    $(this).removeClass("hover"); 
}); 

基本上我想要的DIV cell-container有一個高亮的背景onmouseover。但也要在其中包含<img>添加邊框。我怎樣才能做到這一點?

+0

將您使用'border-color'的CSS屬性更改爲:'border'並查看答案 – 2011-12-26 22:55:39

回答

7

爲什麼不在CSS中做到這一點?

div.cell-container:hover { 
    background-color: silver; 
} 

div.cell-container:hover img.thumbnail { 
    border: 1px solid #000; 
} 
+0

+1顯示使用CSS是多麼容易。 :P – Purag 2011-12-26 22:52:09

+0

不能相信我忘了你可以申請:懸停在CSS哈哈。謝謝。 – Aaron 2011-12-26 22:56:16

+0

+1只有CSS才能做到這一點。爲什麼我不這麼想? – Neel 2014-06-16 18:59:44

4

btw $.hover提供鼠標懸停和鼠標懸停。

$(".cell-container").hover(function() { 
    $(this).addClass("hover"); 
    $(this).children('img').addClass('hover-image'); 
}, function() { 
    $(this).removeClass("hover"); 
    $(this).children('img').removeClass('hover-image'); 
}); 
+0

不需要使用'$(this)'兩次。 – Purag 2011-12-26 22:49:51

+0

是真實的,但我發現這樣更具可讀性。 – 2011-12-26 22:50:36

1
$(".cell-container").hover(function(){ // using hover for shorter syntax 
    $(this) 
     .addClass("hover") // add hover class on mouseover 
     .find("img") // select the child image 
      .addClass("hover-image"); // add hover class 
}, function(){ // mouseout function 
    $(this) 
     .removeClass("hover") // remove hover class 
     .find("img") // select the child image again 
      .removeClass("hover-image"); // remove hover class 
}); 

更多關於hover()here

+0

+1爲公平競爭;)(當然是一個正確的例子) – 2011-12-26 22:53:58

2

DEMO

$(".cell-container").mouseover(function() { 
    $(this).addClass("hover").find('img').addClass('hover-image'); 
}); 

$(".cell-container").mouseout(function() { 
    $(this).removeClass("hover").find('img').removeClass('hover-image'); 
}); 

而且你必須改變你的CSS:

.hover-image { 
    border: 1px solid #000; 
} 
+0

+1用於指出邊框屬性錯誤。 – Purag 2011-12-26 22:51:49

0
$(".cell-container").hover(
    function() { 
    $(this).addClass("hover"); 
    $(this).children("img").addClass("img-hover"); 
    }, 
    function() { 
    $(this).removeClass("hover"); 
    $(this).children("img").removeClass("img-hover"); 
    } 
); 



.hover-image { 
    border: 1px solid #000; 
} 
1

如何:

.cell-container:hover 
{ 
    background-color: silver; 
} 

.cell-container:hover img 
{ 
    border: 1px solid #000; 
} 

只是css。

如果你只是添加樣式類,你應該始終確保你試圖實現的是不可能在CSS(通常是)。