jQuery Mouseover仅适用于父级,而不适用于子级

时间:2019-08-17 18:42:46

标签: javascript jquery html events mouseevent

我有一系列带有box类的div。我想将鼠标悬停在box-1上,然后将ID为img-1的相应图像带到前景。 2和3也是一样。

交互工作良好,除了当我将鼠标悬停在box div内的p标签上时,此操作无效:num返回NaN而不是id中的数字。如何解决此问题,以便当我将鼠标悬停在box-1和box-1的子代上时,它会触发使图像向前移动的功能?请帮忙。谢谢。

    var num;
    $(".box").mouseenter(function(event){
    	num = parseInt(event.target.id.split("-")[1]);
        $("#img-" + num).css("display", "block");
        $("#img-" + num).css("zIndex", 999);
    .mouseleave(function(){
        $("#img-" + num).css("display", "none");
        $("#img-" + num).css("zIndex", 0);
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
        <div class="box" id="box-1">
            <p>title</p>
            <p>caption</p>
        </div>
        <div class="box" id="box-2">
            <p>title</p>
            <p>caption</p>
        </div>
        <div class="box" id="box-3">
            <p>title</p>
            <p>caption</p>
        </div>
        <img id="img-1" style="display:none"/>
        <img id="img-2" style="display:none"/>
        <img id="img-3" style="display:none"/>
    </div>

1 个答案:

答案 0 :(得分:0)

在父“框”以及子p元素上设置事件。

您不必担心将鼠标悬停在子元素上,因为当您这样做时,也将鼠标悬停在父元素上。您也不必担心将图像放到前景中,因为未显示的图像不会首先出现在页面上。

阅读以下评论:

var num = null;
// JQuery recommends using .on() instead of shorthand event methods
// By setting the event on the parent box as well as the child <p>'s the problem is solved.
$(".box, .box p").on("mouseover", function(event){
  // .closest() takes a selector and looks for a match as the nearest ancestor 
 	num = parseInt(this.closest(".box").id.split("-")[1]);
  $("#img-" + num).removeClass("hidden"); // Work with CSS classes not inline styles
});

$(".box, .box p").on("mouseout", function(){
  $("#img-" + num).addClass("hidden");
});
.hidden {display:none;}
.box { border:1px dashed grey; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
        <div class="box" id="box-1">
            <p>title</p>
            <p>caption</p>
        </div>
        <div class="box" id="box-2">
            <p>title</p>
            <p>caption</p>
        </div>
        <div class="box" id="box-3">
            <p>title</p>
            <p>caption</p>
        </div>
        <img id="img-1" class="hidden" alt="img-1">
        <img id="img-2" class="hidden" alt="img-2">
        <img id="img-3" class="hidden" alt="img-3">
    </div>