如何在<a>?

时间:2016-05-05 08:45:00

标签: javascript jquery

I want the div to change background when hovered on. But it doesn't change background when the text inside the div is hovered on instead. This is what I tried, but ALL the background divs change. I also tried a > img instead of just img in my handler functions, but it didn't work at all.

function handlerIn() {
    $("img").css({"opacity":1});
}

function handlerOut() {
    $("img").css({"opacity":0});
}

$("a").mouseenter(handlerIn).mouseleave(handlerOut);

3 个答案:

答案 0 :(得分:1)

a > img不起作用,因为img不是aparent > child)的孩子,而是后代(achestor descendant)。

所以你的css规则应该是这样的:

a:hover  img {
  opacity: 1;
}

所以你根本不需要jQuery,但如果你想使用jQuery,那么你需要使用a元素作为根目录搜索img否则您将找到所有img元素。

function handlerIn() {
  $(this).find('img').css({
    "opacity": 1
  });
}

function handlerOut() {
  $(this).find('img').css({
    "opacity": 0
  });
}

$("a").mouseenter(handlerIn).mouseleave(handlerOut);

答案 1 :(得分:0)

你不需要jquery来完成这项工作。

可以通过css完成:

#kpop:hover, #fashion:hover, #martialarts:hover, #nature:hover{
  background: url('http://www.dike.lib.ia.us/images/sample-1.jpg/image_preview');
}

答案 2 :(得分:0)

我不确定这是正确的,为什么你不使用 hover() 功能? http://codepen.io/soulister/pen/MyZrPy