Angular - 当鼠标悬停在按钮

时间:2016-08-19 16:50:16

标签: javascript jquery html angularjs frontend

我想实现一个按键通话按钮,当我按下鼠标时启用语音,并在我释放鼠标时禁用语音。这是我现在的代码:

    <button ng-mousedown="enablePushToTalk()" ng-mouseup="disablePushToTalk()" class="btn"> PushToTalk </button>

问题场景是:

  1. 用户点击按键通话按钮(mouseDown:调用enablePushToTalk)
  2. 用户将鼠标从按钮移开
  3. 用户释放鼠标:永远不会调用mouseUp事件,因此永远不会调用disablePushToTalk!所以Push To Talk保持启用状态。
  4. 这是一个gif:

    Buggy behavior

    如何确保每次调用“enablePushToTalk”时都会调用“disablePushToTalk”?

1 个答案:

答案 0 :(得分:1)

如何将ng-mouseup事件侦听器添加到父元素?

使用上述想法为您的问题创建了一个jsBin。

解决方案1:

// HTML

<body style='height:500px;border:1px solid black;' ng-controller="MyCtrl" ng-mouseup='disable()'>
<div >
  <button ng-mousedown="enablePushToTalk()" ng-mouseup="disablePushToTalk()" class="btn"> PushToTalk </button>
</div>
</body>

// JS

function MyCtrl($scope) {
    $scope.name = 'Superhero';
    var isMouseUp = false;
    $scope.enablePushToTalk = function(){console.log('mouseup');isMouseUp=true;}
    $scope.disablePushToTalk = function(){console.log('mousedown');isMouseUp=false;}
    $scope.disable = function(){if(!isMouseUp) return;console.log('mousedown from body');isMouseUp=false;}
}

jsBin链接:http://jsbin.com/nedijudaga/edit?html,js,console,output

解决方案2:

仅将ng-mouseup事件添加到父元素而不是button上就可以了。