2011-12-26 16 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は、背景を強調表示します。しかし、内に含まれている<img>にも境界線を追加してください。どうすればこれを達成できますか?

+0

'border-color'を使用したCSSプロパティを' border'に変更して回答を見てください –

答えて

7

CSSでこれを行うのはなぜですか?

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

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

+1とCSSの使いやすさを示します。 :P – Purag

+0

申し訳ありませんが私はあなたが適用できることを忘れて信じられない:CSSの笑いでホバー。ありがとう。 – Aaron

+0

+1 CSSだけでそれを行うには、素晴らしい方法です。なぜ私はそれを考えなかったのですか? – Neel

4

btw $.hoverは、マウスオーバーとマウスアウトの両方を提供します。 hover()here

$(".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) 'を2回使用する必要はありません。 – Purag

+0

真実ですが、私はそれをこのようにより読みやすくしています。 –

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 
}); 

より。

+0

+1公正な競争;)(正確な例はもちろん) –

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

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では不可能であることを確認する必要があります(通常はそうです)。

関連する問題