簡體   English   中英

將鼠標懸停在孩子上方,但將父div排除在外

[英]Hovering over child but exclude parent div

我在同一個類的父div內有一個子div。 現在,如果將鼠標懸停在父級內的子div上方,則邊框將同時添加到子級和父級中。 我要確保只有被懸停的div才會應用邊框。

$(document).ready(function () {
                            $(".content").hover(function () {
                                $(this).parents().removeClass('divHoverBorder');
                                $(this).siblings().removeClass('divHoverBorder');
                                $(this).addClass("divHoverBorder");
                                $(this).parents().find(".addContentItemDiv").hide();
                                $(this).find(".addContentItemDiv:first").show();

                            }, function () {
                                $(this).removeClass("divHoverBorder");
                                $('.addContentItemDiv').hide();
                            });
                        });

<div class="content" style="width: 500px; height: 300px;">
    <div class="content" style="width: 500px;  height: 200px;">

</div>
</div>

這是我所指的JSFiddle:

JS小提琴

您的主要問題在這里:

<div class="content" style="width: 500px; height: 300px;">
    <div class="content" style="width: 500px;  height: 200px;">    
</div>

由於兩個div具有相同的類,因此您實際上要在兩個div上放置一個懸停事件,而您的JQuery無法區分它們。

由於您表示必須以這種方式進行操作,因此您可以執行以下操作:

$(document).ready(function () {
    $(".content").mouseover(function (e) {
        $(this).parents().removeClass('divHoverBorder');
        $(this).siblings().removeClass('divHoverBorder');
        $(this).addClass("divHoverBorder");
        $(this).parents().find(".addContentItemDiv").hide();
        $(this).find(".addContentItemDiv:first").show();
        var p = $(this).parent('.content');
        if (p.length) { p.removeClass('divHoverBorder'); e.stopPropagation(); }
    });
    $('.content').mouseout(function (e) {
        $(this).removeClass("divHoverBorder");
        $('.addContentItemDiv').hide();
    });
});

請注意,您不能使用hover 懸停在JQuery中使用mouseentermouseleave事件,這將防止在將鼠標從子級移到父級時觸發事件。 我們必須移除父邊界(在進入子邊界的情況下) 停止傳播以防止其重新應用其自身邊界。

這是來自JQuery文檔的有關mouseentermouseover之間的區別的說明:

mouseenter事件與mouseover的不同之處在於它處理事件冒泡的方式。 如果在此示例中使用mouseover,則當鼠標指針移到Inner元素上時,將觸發處理程序。 這通常是不受歡迎的行為。 另一方面,mouseenter事件僅在鼠標進入其綁定元素而不是后代時才觸發其處理程序。 因此,在此示例中,當鼠標輸入Outer元素而不是Inner元素時,將觸發處理程序。

您更新的小提琴: http : //jsfiddle.net/tTUaj/10/

使用這樣的東西:

 $(".content").hover(function (ev) {
    if ($(ev.currentTarget).parent().hasClass(".content")){
     //this is a child
    } else {
    //this is a parent
    }
 });

我會推薦這樣的東西: http : //jsfiddle.net/3SVGe/1/

$(".cell").hover(function () {
    $(".cell").removeClass("over");
    $(this).addClass("over");
}, function () {
    $(this).removeClass("over");
});

您的問題是,將鼠標懸停在子元素上時,將在父元素上觸發懸停事件。 這回避了問題。

或者,您可以采用稍微復雜一點的解決方案,該解決方案允許您先將鼠標懸停在父對象,子對象上,再到父元素上。 一個示例在這里: http : //jsfiddle.net/3SVGe/2/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM