我想出了一個解決方案,我使用的是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