我想出了一个解决方案,我使用的是angularjs,所以我为它创建了一个指令。
.directive('disableBackspace', function() {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var entered = false;
element.bind('focus',function() {
// remember that it's focused
entered = true;
});
element.bind('blur',function() {
// remember that it's blurred
entered = false;
});
scope.$on('$locationChangeStart', function(event, next, current) {
// in angular it's not onbeforeunload but $locationChangeStart
// prevent navigation if it's entered
if(entered) {
event.preventDefault();
}
});
element.bind("keydown keypress", function (event) {
// this is for other form elements
if(event.which === 8) {
scope.$apply(function(){
scope.$eval(attrs.myEnter);
});
event.preventDefault();
}
});
}
};
})
您可以使用该指令是这样的:
<select disable-backspace>
<option>123</option> ...
的指令监听onfocus和的onblur输入的事件和位置是变化的,它会检查是否输入被聚焦。完美的作品。希望这可以帮助某人。
鼠标在下拉菜单上如何? http://stackoverflow.com/questions/2709474/is-there-a-way-to-determine-if-a-select-dropdown-menu-is-open – misha130
@ misha130有趣,但检测后该怎么办? –
为keydown启动事件并在其退格时启动preventDefault。在mouseexit停止事件 – misha130