gpt4 book ai didi

javascript - 根据按下按钮的时间将两个功能绑定(bind)到按钮

转载 作者:行者123 更新时间:2023-11-30 00:13:17 25 4
gpt4 key购买 nike

我想要一个按钮,如果按下时间超过 3 秒,它会调用不同的功能。以下代码适用于鼠标事件,但在具有触摸事件的移动设备上会失败:

angular.module('myApp', []).controller('myCtrl', function($scope, $timeout) {

var mapService = {
setHome: function() {
console.log("setHome called");
},

goHome: function() {
console.log("goHome called");
}
};

var _homeDownTimeout = null;
var _homeWasSet = false;

$scope.homeDown = function() {
_homeDownTimeout = $timeout(function() {
mapService.setHome();
_homeWasSet = true;
}, 3000);
};

$scope.homeUp = function() {
if (_homeDownTimeout) {
$timeout.cancel(_homeDownTimeout);
}
if (!_homeWasSet) {
mapService.goHome();
} else {
_homeWasSet = false;
}
};

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">

<button class="button icon ion-home button-map" ng-mousedown="homeDown()" ng-mouseup="homeUp()">HOME</button>

</div>

最佳答案

在 Chrome 中使用移动模拟器,看来你的问题不在于代码,而是行为是在你按住它时选择元素,这会中断 mouseup 事件。

一个简单的解决方法是设置 user-select:none在按钮 CSS 中,如 this answer 中所述.

angular.module('myApp', []).controller('myCtrl', function($scope, $timeout) {

var mapService = {
setHome: function() {
console.log("setHome called");
},

goHome: function() {
console.log("goHome called");
}
};

var _homeDownTimeout = null;
var _homeWasSet = false;

$scope.homeDown = function() {
_homeDownTimeout = $timeout(function() {
mapService.setHome();
_homeWasSet = true;
}, 3000);
};

$scope.homeUp = function() {
if (_homeDownTimeout) {
$timeout.cancel(_homeDownTimeout);
}
if (!_homeWasSet) {
mapService.goHome();
} else {
_homeWasSet = false;
}
};

});
button {
-webkit-touch-callout: none; /* iOS Safari */
-webkit-user-select: none; /* Chrome/Safari/Opera */
-khtml-user-select: none; /* Konqueror */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* IE/Edge */
user-select: none; /* non-prefixed version, currently
not supported by any browser */
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">

<button class="button icon ion-home button-map" ng-mousedown="homeDown()" ng-mouseup="homeUp()">HOME</button>

</div>

关于javascript - 根据按下按钮的时间将两个功能绑定(bind)到按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35623506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com