在 jQuery 中检测背景点击

发布于 2024-08-17 23:07:26 字数 847 浏览 3 评论 0原文

假设我有以下 HTML:

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

我想这样做,以便当我单击跨度时,它将触发一些事件(例如使文本变为粗体),这很简单:

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

但是现在当我单击元素之外时,我想要要触发的另一个事件(例如使文本正常粗细)。我需要以某种方式检测不在 span 元素内部的点击。这与blur() 事件非常相似,但适用于非INPUT 元素。顺便说一句,我不介意是否仅在 DIV 元素内检测到此点击,而不是在页面的整个正文中检测到。

我尝试使用以下方法在非 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

另一种解决方案是在单击事件中读取事件的目标。这是一个以这种方式实现它的示例:

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

我想知道是否有一个更优雅的解决方案,例如blur()。

Say I have the following HTML:

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

I want to make it so that when I click on span, it will trigger some event (e.g. to make the text bold), that's easy:

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

But now I when I click away from the element, I want another event to trigger (e.g. to make the text normal weight). I need to detect, somehow, a click not inside the span element. This is very similar to the blur() event, but for non INPUT elements. I don't mind if this click is only detected inside the DIV element and not the entire BODY of the page, btw.

I tried to get an event to trigger in non-SPAN elements with the following:

$('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

Another solution would be to read the event's target inside the click event. Here's an example of implementing it this way:

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

I was wondering if there was a more elegant solution like blur() though.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

卸妝后依然美 2024-08-24 23:07:26

根据我的研究,我认为 stopPropagation 函数是最合适的。
例如:

$("#something_clickable a").click(function(e) {
   e.stopPropagation();
})

请参阅如何防止在单击子锚点时触发父级的 onclick 事件? 类似的问题。

From what I've researched, I think the stopPropagation function is most appropriate.
For example:

$("#something_clickable a").click(function(e) {
   e.stopPropagation();
})

See How do I prevent a parent's onclick event from firing when a child anchor is clicked? for a similar question.

纵山崖 2024-08-24 23:07:26

你的最后一个方法应该效果最好,即使它很混乱。这里有一些改进:

$('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');
        }
    });
});

它不干净,但应该可以工作。没有不必要的绑定,这应该是万无一失的(没有误报等)。

Your last method should work best even if it's messy. Here's a little refinement:

$('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');
        }
    });
});

It's not clean, but it should work. No unnecessary binds and this should be foolproof (no false positives etc).

溺渁∝ 2024-08-24 23:07:26

我想出了一个解决这个问题的方法......

在 jQuery 发布之前, -clicked-with-javascript.aspx" rel="nofollow noreferrer">确定是否使用 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;
}

I came up with a solution to this problem before jQuery was released...

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;
}
无敌元气妹 2024-08-24 23:07:26

如果您从跨度的单击处理程序返回 false,您将阻止事件冒泡,这将使 div 单击处理程序无法运行。

If you return false from your click handler for the span you'll prevent the event from bubbling, which will keep the div click handler from running.

圈圈圆圆圈圈 2024-08-24 23:07:26
$(':not(span)').click(function(){
    //dostuff
})
$(':not(span)').click(function(){
    //dostuff
})
九命猫 2024-08-24 23:07:26

使用 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 中运行。我自己没有测试过,所以可能是这样!

此外,tabIndex-1 表示可以单击该元素,但无法通过键盘获得焦点。如果您希望通过 TabShift+Tab 获得焦点,您可以将其更改为 0

Using the tabIndex property, you can actually make arbitrary elements focusable:

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);

Unfortunately, this example probably won't work in IE. I haven't tested it myself, so it might!

Also, a tabIndex of -1 means the element can be clicked on, but can't be focused with the keyboard. You can change it to 0 if you want it to be focusable with Tab or Shift+Tab.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文