Link retains focus when clicking it, then moving the mouse off it. But loses focus when I mousedown link but then move mouseoff link and release mouse
http://jsfiddle.net/nicktheandroid/bD37R/2/
I'm trying to get rid of an element still having focus if the user mousedowns on a link, but then moves the mouse away from the link - while still holding down the 开发者_运维百科mouse button, and releases the mouse button. To me, this means the user realized they didn't want to click the link, before they released the mouse button - so they didn't release the mouse button over the link, but instead moved the mouse away from the link, then released the mouse button.
The element could be a link, or a div/span with active and focus styles, it works the same.
In my example, if I click on one of the divs it acts as I would like it to, but then when I mouseout, it takes the focus away, which shouldn't happen. The focus should only be taken away if the user mousedowns on the link/div, but then drags the mouse off of the element and then releases the mouse button. But I want the element to keep the focus style if they click the element, then after clicking, hovering off of the element. That's my problem, if I click the element, then after clicking I move my mouse off the element, it loses focus. I know my jQuery isn't right, for some reason i'm having a hard time figuring out what the jQuery should look like.
$('div').mousedown(function(){
$(this).mouseleave(function(){
if ($(this).mousedown()) {
$(this).blur()
}
})
})
This is the best I could come up with. Not elegant, but got the job done. The problem is that the focus event occurs on mouseup. But you don't know where the mouseup event is going to occur. So we have to track it using a global instead.
http://jsfiddle.net/bD37R/4/
//keep track of whether the mouse is down or up
var mouseDown;
document.body.onmousedown = function() {
mouseDown = true;
}
document.body.onmouseup = function() {
mouseDown = false;
}
//store currently selected element
var activeElement;
//on mouse leave check whether the mouse is down. if so store the element for
//release on mouse up
$('div').mouseleave(function() {
console.log(mouseDown);
if (mouseDown) {
console.log('blur');
activeElement = $(this);
}
else { activeElement = null; }
})
//release the element
$(document).mouseup(function() {
if (activeElement) {
console.log('active Element');
activeElement.blur();
}
});
精彩评论