2010-01-13 78 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