2010-01-13 79 views
3

說我有以下HTML:檢測背景點擊jQuery的

<div> 
    <span>span text</span> div text <span>some more text</span> 
</div> 

我想讓它這樣,當我點擊跨度,它會引發一些事件(例如,使文本加粗),這是易:

$('span').click(...) 

但現在我當我從元素點擊即可,我想另一個事件來觸發(例如,使文本正常體重)。我需要以某種方式檢測不在span元素內部的點擊。這與blur()事件非常相似,但是對於非INPUT元素。我不介意是否只在DIV元素內檢測到該點擊,而不是該頁面的整個BODY,順便說一句。

我試圖讓一個事件在非SPAN元素來觸發下列要求:

$('div').click(...) // triggers in the span element 
$('div').not('span').click(...) // still triggers in the span element 
$('div').add('span').click(...) // triggers first from span, then div 

另一種解決辦法是閱讀活動的目標click事件裏面。下面是實現這種方式的一個例子:

$('div').click(function(e) { 
    if (e.target.nodeName != "span") 
    ... 
}); 

我想知道是否有像模糊的更優雅的解決方案()雖然。

回答

2

即使雜亂無章,您的最後一種方法也應該是最好的。這裏有一點改進:

$('span').click(function() { 
    var span = $(this); 
    // Mark the span active somehow (you could use .data() instead) 
    span.addClass('span-active'); 

    $('div').click(function(e) { 
     // If the click was not inside the active span 
     if(!$(e.target).hasClass('span-active')) { 
      span.removeClass('span-active'); 
      // Remove the bind as it will be bound again on the next span click 
      $('div').unbind('click'); 
     } 
    }); 
}); 

它不乾淨,但它應該工作。沒有不必要的綁定,這應該是萬無一失的(沒有誤報等)。

0
$(':not(span)').click(function(){ 
    //dostuff 
}) 
+0

您是否意識到這會將單擊事件處理程序分配給*噸*元素?遠非理想。 – 2010-01-13 21:25:55

+0

他說他想要的只是跨度 – helloandre 2010-01-13 21:33:16

+0

但是之後他應該利用事件冒泡來達到性能的原因。 – DanMan 2010-12-21 18:10:34

1

,我想出了一個解決的jQuery之前這個問題被釋放......

Determine if any Other Outside Element was Clicked with Javascript

document.onclick = function() { 
    if(clickedOutsideElement('divTest')) 
    alert('Outside the element!'); 
    else 
    alert('Inside the element!'); 
} 

function clickedOutsideElement(elemId) { 
    var theElem = getEventTarget(window.event); 

    while(theElem != null) { 
    if(theElem.id == elemId) 
     return false; 

    theElem = theElem.offsetParent; 
    } 

    return true; 
} 

function getEventTarget(evt) { 
    var targ = (evt.target) ? evt.target : evt.srcElement; 

    if(targ != null) { 
    if(targ.nodeType == 3) 
     targ = targ.parentNode; 
    } 

    return targ; 
} 
+0

它並不需要爲jQuery進行更改。 – 2010-01-13 21:32:17

1

如果你從你的點擊處理程序返回false你會阻止跨度從冒泡的事件,這將保持div點擊處理程序運行。

0

使用tabIndex屬性,你實際上可以使任意元素可聚焦:

var node = document.createElement("span"); 
node.tabIndex = -1; 

node.addEventListener("focus", function() { 
    // clicked the element... 
}, true); 

node.addEventListener("blur", function() { 
    // clicked away from the element... 
}, true); 

不幸的是,這個例子可能不會在IE瀏覽器。我沒有自己測試過,所以它可能!

另外,的-1表示該元素可以點擊,但不能用鍵盤聚焦。如果您希望它可以通過TabShift+Tab進行調整,您可以將其更改爲0