jQuery:向元素的子元素添加类

3

HTML:

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

基本上,我希望在鼠标悬停时使
cell-container
具有突出显示的背景。但同时也要为<img>添加边框。我该如何实现这一点?

将您使用的CSS属性border-color更改为border,然后查看答案。 - Roko C. Buljan
6个回答

7
为什么不直接在CSS中实现这个效果呢?
div.cell-container:hover {
  background-color: silver;
}

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

不敢相信我竟然忘记了在CSS中可以使用:hover。哈哈,谢谢。 - Aaron
+1 这是一个非常优秀的只用 CSS 实现的方法。为什么我没想到呢? - Neel

4

顺便说一下,$.hover方法提供了鼠标悬浮和移出事件的处理。

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

不需要两次使用$(this) - Purag

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

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() 的更多信息 在这里


+1 为了公平的竞争 ;) (当然,也要正确的例子) - Roko C. Buljan

1

这样怎么样:

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

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

只是 CSS。

如果你只是添加样式类,你应该始终确保你想要实现的效果在 CSS 中无法实现(通常是可以的)。


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接