这适用于IE,但我无法在Opera或Firefox中使用它。当且仅当当前焦点是SELECT下拉列表时,我想阻止Backspace导航。
<html>
<body>
<select id="testselect">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<script language="javascript">
document.getElementById("testselect").onkeydown = function(e) {
if(!e) {
e = event;
}
alert(e.keyCode);
if (e.keyCode == 8 || e.keyCode == 46) {
e.returnValue = false;
e.cancelBubble = true;
if (e.stopPropagation) { e.stopPropagation(); alert("stoppropagation");}
if (e.preventDefault) { e.preventDefault(); alert("preventdefault");}
return false;
}
};
</script>
</body>
</html>
答案 0 :(得分:9)
使用jquery - 仅用于选择下拉列表
$(document).ready(function(){
//for IE use keydown, for Mozilla keypress
//as described in scr: http://www.codeproject.com/KB/scripting/PreventDropdownBackSpace.aspx
$('select').keypress(function(event){if (event.keyCode == 8) {return false;}});
$('select').keydown(function(event){if (event.keyCode == 8) {return false;}});
}
对于页面中的所有元素,输入控件和textarea除外如下
<script type="text/javascript">
//set this variable according to the need within the page
var BACKSPACE_NAV_DISABLED = true;
function fnPreventBackspace(event){if (BACKSPACE_NAV_DISABLED && event.keyCode == 8) {return false;}}
function fnPreventBackspacePropagation(event){if(BACKSPACE_NAV_DISABLED && event.keyCode == 8){event.stopPropagation();}return true;}
$(document).ready(function(){
if(BACKSPACE_NAV_DISABLED){
//for IE use keydown, for Mozilla keypress
//as described in scr: http://www.codeproject.com/KB/scripting/PreventDropdownBackSpace.aspx
$(document).keypress(fnPreventBackspace);
$(document).keydown(fnPreventBackspace);
//Allow Backspace is the following controls
$('input').keypress(fnPreventBackspacePropagation);
$('input').keydown(fnPreventBackspacePropagation);
$('textarea').keypress(fnPreventBackspacePropagation);
$('textarea').keydown(fnPreventBackspacePropagation);
}
});
</script>
答案 1 :(得分:2)
这比我想象的要棘手。根据您阻止用户退出页面的原因,this之类的内容可能对您有用:
<script type="text/javascript">
var bShowWarning = false;
document.getElementById("testselect").onkeydown = function(e) {
if (!e) {
e = event;
}
if (e.keyCode == 8 || e.keyCode == 46) {
bShowWarning = true;
}
};
function UnLoadWindow() {
if (!bShowWarning) return;
return 'If you leave the page your data will be lost.';
}
window.onbeforeunload = UnLoadWindow;
</script>
答案 2 :(得分:1)
嗯,事实证明Opera需要在 onkeypress 事件中取消事件,而不是onkeydown。
答案 3 :(得分:0)
您可能希望从this article查看项目的源代码。他详细介绍了他在不同浏览器中如何与退格键竞争。