簡體   English   中英

停止懸停並單擊沒有特定類屬性的元素

[英]Stop hover and click on element with not specific class attribute

我想在沒有特定類名屬性的元素上禁用懸停(並單擊):

<svg>
   <path class="myClass"></path>
   <path class="myClass active"></path>
</svg>

基本上,如果路徑沒有屬性className“ active”,則不要懸停或單擊

嘗試過:

    if (!$("path").hasClass("active")) {
        $(this).unbind('mouseenter mouseleave');
    };

但我相信我應該使用.attr("class"..)因為它是svg path

您只能將事件處理程序添加到具有.active類的元素中。 但是,如果您不能這樣做,請使用:not()選擇器選擇沒有.active類的元素。

$("path:not(.active)").unbind('mouseenter mouseleave')

本演示使用.attr()函數。 這樣,您將必須遍歷每個所需的元素並循環其類列表(如果存在),如果不包含該類,則查看它是否包含.active類,然后取消綁定該元素的事件。

 $('p').on('mouseenter', function() { $(this).css('background', 'blue'); }) $('p').on('mouseleave', function() { $(this).css('background', 'black'); }) $('p').each(function(indx, elem) { var activeNotFound = 1; var classes = []; if ($(elem).attr('class') !== undefined) { // check if elem has attribute class classes = $(elem).attr('class').split(" "); // split into array the attribute class $.each(classes, function(ndx, classname) { // loop each class to check if active exist if (classname === 'active') { activeNotFound = 0; } // removed the else part. }); } if (activeNotFound) { // if no active class found unbind events $(elem).unbind('mouseenter mouseleave') } }) 
 div p { width: 100px; height: 100px; background: #000; border: 5px solid #000; } p.active { border: 5px solid red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h4>Note: I used a different element for this demo. Just change it to the needed elements and also update the script</h4> <div> <p class="myClass"></p> <p class="myClass active"></p> <p></p> </div> 

暫無
暫無

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

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