点击时停止元素消失 [英] Stop element from disappearing when clicked

查看:79
本文介绍了点击时停止元素消失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个简单的jQuery插件,当它有焦点时,它会动态地在文本框下放置一个div。我已经能够在所有浏览器中获得该位置。



我必须在焦点上附加两个事件处理程序 blur 文本框的事件。它的工作原理没问题,但问题在于,即使我们点击它,放置在文本框下的div也会关闭。现在它是有道理的,为什么它会发生,这是因为文本框失去焦点,但有没有办法阻止它发生?



我试着将它附加到模糊事件处理程序 -

  if($(mainElem).is(:focus))return; 

其中 mainElem 是显示的div下面的文本框。



这是一个 jsFiddle来说明这个问题。

解决方案

您无法使用 blur 事件,如果你想在显示的div中放置可点击的元素。解决此问题的一种方法是将您的事件侦听器绑定到更多全局元素,如文档,然后过滤出目标。



这是一个代码示例:

  $(document).on('click',function(e){ 
var targetEl = e.target,
parent = $(e.target).parents()[0];
if(relElem [0] === targetEl || self [0 ] === targetEl || self [0] ===父){
$(mainElem).show();
} else {
$(mainElem).hide();
}
});

以下是您的小提琴更新: http://jsfiddle.net/9YHKW/6/

I'm writing a simple jQuery plugin that will dynamically place a div under a text box whenever it has focus. I've been able to get the position just about right in all the browsers.

I have to attach two event handlers as well on the focus and blur events of the textbox. And it works okay, but the problem is that the div that has been placed under the textbox closes even when we click on it. Now it makes sense why it would so happen, it's because the textbox loses focus, but is there a way I can stop it from happening?

I tried attaching this to the blur event handler -

if($(mainElem).is(":focus")) return;

where mainElem is the div that is shown below the textbox.

Here is a jsFiddle to illustrate the problem.

解决方案

You are not going to be able to use the blur event if you want to place "clickable" elements in the div that shows. One way to solve this is to bind your event listener to a more global element like the document and then filter out the targets.

Here is a code sample:

$(document).on('click', function (e) {
      var targetEl = e.target,
          parent = $(e.target).parents()[0];
      if (relElem[0] === targetEl || self[0] === targetEl || self[0] === parent) {
          $(mainElem).show();
      } else {
          $(mainElem).hide();
      }
 });

Here is an update to your fiddle: http://jsfiddle.net/9YHKW/6/

这篇关于点击时停止元素消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆