【问题标题】: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单击链接时,链接会保持焦点,然后将鼠标移开。但是当我 mousedown 链接然后移动 mouseoff 链接并释放鼠标时会失去焦点
【发布时间】:2011-08-28 06:59:08
【问题描述】:

http://jsfiddle.net/nicktheandroid/bD37R/2/

如果用户在链接上按下鼠标,然后将鼠标从链接上移开,我正在尝试摆脱仍然具有焦点的元素 - 同时仍然按住鼠标按钮,然后释放鼠标按钮。对我来说,这意味着用户在释放鼠标按钮之前意识到他们不想点击链接 - 所以他们没有在链接上释放鼠标按钮,而是将鼠标从链接上移开,然后释放鼠标按钮。

元素可以是链接,也可以是具有活动和焦点样式的 div/span,它们的工作方式相同。

在我的示例中,如果我单击其中一个 div,它会按照我的意愿进行操作,但是当我鼠标移出时,它会将焦点移开,这是不应该发生的。仅当用户在链接/div 上按下鼠标,然后将鼠标拖离元素并释放鼠标按钮时,才应取消焦点。但是我希望元素在单击元素时保持焦点样式,然后在单击后将鼠标悬停在元素之外。那是我的问题,如果我单击元素,然后单击后将鼠标从元素上移开,它就会失去焦点。我知道我的 jQuery 不正确,出于某种原因,我很难弄清楚 jQuery 应该是什么样子。

$('div').mousedown(function(){
    $(this).mouseleave(function(){
        if ($(this).mousedown()) {
            $(this).blur()
        }
    })
})

【问题讨论】:

  • 你的解释有点混乱。你能通过明确解释你想要发生的事情来帮忙吗?如 - 1. 点击,不要放开。 div 变为蓝色。 2. 将鼠标从 div 上移开并松开。我预计... ?也适用于点击和放手的情况。
  • 我对您所描述的与默认锚行为有何不同感到困惑。 mouseenter:hover, mousedown:active, mouseleave:default, mouseenter:active, mouseup:click

标签: jquery focus hyperlink mouseout mousedown


【解决方案1】:

这是我能想到的最好的。不优雅,但完成了工作。问题是焦点事件发生在 mouseup 上。但是你不知道 mouseup 事件会在哪里发生。所以我们必须使用全局来跟踪它。

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

【讨论】:

    猜你喜欢
    • 2016-08-10
    • 2012-05-25
    • 1970-01-01
    • 2011-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多