3 回答

TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超5個(gè)贊
這段代碼至少在IE和Firefox中解決了該問(wèn)題(尚未測(cè)試過(guò)其他任何工具,但即使在其他瀏覽器中也存在問(wèn)題,我也給了它合理的工作機(jī)會(huì))。
// Prevent the backspace key from navigating back.
$(document).unbind('keydown').bind('keydown', function (event) {
if (event.keyCode === 8) {
var doPrevent = true;
var types = ["text", "password", "file", "search", "email", "number", "date", "color", "datetime", "datetime-local", "month", "range", "search", "tel", "time", "url", "week"];
var d = $(event.srcElement || event.target);
var disabled = d.prop("readonly") || d.prop("disabled");
if (!disabled) {
if (d[0].isContentEditable) {
doPrevent = false;
} else if (d.is("input")) {
var type = d.attr("type");
if (type) {
type = type.toLowerCase();
}
if (types.indexOf(type) > -1) {
doPrevent = false;
}
} else if (d.is("textarea")) {
doPrevent = false;
}
}
if (doPrevent) {
event.preventDefault();
return false;
}
}
});

TA貢獻(xiàn)1862條經(jīng)驗(yàn) 獲得超7個(gè)贊
該代碼在所有瀏覽器上都有效,并且當(dāng)不在form元素上,或者form元素被禁用| readOnly時(shí),將吞下退格鍵。它也是有效的,當(dāng)它在鍵入的每個(gè)鍵上執(zhí)行時(shí)很重要。
$(function(){
/*
* this swallows backspace keys on any non-input element.
* stops backspace -> back
*/
var rx = /INPUT|SELECT|TEXTAREA/i;
$(document).bind("keydown keypress", function(e){
if( e.which == 8 ){ // 8 == backspace
if(!rx.test(e.target.tagName) || e.target.disabled || e.target.readOnly ){
e.preventDefault();
}
}
});
});
添加回答
舉報(bào)