Blur event handler is blocked by jquery preventDef

2019-07-31 09:50发布

问题:

I'm working on an interactive web application, currently set up on http://picselbocs.com/projects/goalcandy (user: demo@demo.com, password: demo). It allows you to drag items containing images and/or text from the left sidebar onto the workspace on the right and resize/edit them, among other things.

To edit text on created objects, you simply click on a text field, either title or comment. That <span> element gets replaced with a <textarea> through which you can then edit the content. When the "blur" event occurs, the textarea disappears and its value is added to the <span> element. The problem is that clicking on the object's image (if it has both an image AND text fields) prevents the "blur" event from firing.

I've used the following snippet to prevent images from being dragged separately from the parent objects, and just found out that this is what's causing the issue. But I can't not use this, and at the same time I have to not use it:

$(document).on('mousedown dragstart', 'img', function(event) { event.preventDefault(); });  

How can I get around this problem and allow the onblur event handler to run even when clicking the image, but at the same time maintain the default behavior prevention?

PS: The alert('blur') call allows me to monitor when the event fires.

回答1:

You use some variable say

var locks = {}; 
locks.textarea_lock = false;

Then clicking on textarea set locks.textarea_lock = true; In image handler check this lock:

$(document).on('mousedown dragstart', 'img', function(event) { 
    if (locks.textarea_lock) {
        return;
    }
    event.preventDefault(); 
});  

In "blur" handler unlock variable locks.textarea_lock = false;.