开发者

Conditional removal when focusing out

I have the following HTML:

<input type="text" id="myText">
<div id="myDiv">

When a user focuses out of the text field, I would like to remove #myDiv, ONLY if the user focused out to an area which is not in the DIV itself.

So far I have the code to remove the div no matter where the user clicked on the screen. What do I need to add to the fo开发者_运维知识库llowing code in order to prevent the removal of the div if the user click inside it?

$("#myText").focusout(function(evt) {
    $("#myDiv").remove();
});


This is what you are looking for. When the blur event is fired, you can access the element that was focused and you can then check the id of the element to see if it matches the id on the div. If it doesn't match, then remove the div.

$("#myText").blur(function(e){    
  var target = e.originalEvent.explicitOriginalTarget||document.activeElement;

  if ($(target).closest("#myDiv").length == 0 && target.id != "myDiv")
    $("#myDiv").remove();
});

Here is a quick example I put together on jsbin: http://jsbin.com/iwari3/10 Let me know if that is what you are looking for

Updated Since the original version wasn't working in Chrome, I decided to take a different approach and it seems to be working in IE/FF/Chrome.

var $myDiv = $("#myDiv"),
    $myText = $("#myText");

 $myText.blur(function(e){        
    if (!$myDiv.data("focused"))
      $myDiv.remove();

    $myDiv.data("focused", false);
 });

 $myDiv.mousedown(function(e){
    $(this).data("focused", true)
 });

This new method will now store a focused bit on #myDiv on mousedown which gets fired before the blur event. In the blur of the textbox we check to see if the focused bit was set. The focused bit is then reset back to false to handle cases where the textbox is clicked in and out of multiple times.

Here is an updated jsbin.com example: http://jsbin.com/iwari3/11


you can have a hidden field with a flag value .

on clicking inside div set the hidden field value to 1.

you should do this before you call remove();

before calling div check this flag and remove.

after removing unset the flag

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜