有些時候我們希望整個頁面的表單進入「唯讀」狀態,使用者只能看不能改。下面這個函數會遍歷各類元件,透過阻止聚焦與包裹遮罩的方式達到唯讀效果,對 input、select、textarea 乃至 img 都適用。
/**
* 將頁面設置為唯讀
*/
var setReadOnly = function() {
var input = $("input");
input.each(function(i) {
$(this).attr("onfocus", "this.blur();return false;");
$(this).wrap(function() {
return '<span onmousemove="this.setCapture();" onmouseout="this.releaseCapture();" />';
});
});
var select = $("select");
select.each(function(i) {
$(this).attr("onfocus", "this.blur();return false;");
$(this).wrap(function() {
return '<span onmousemove="this.setCapture();" onmouseout="this.releaseCapture();" />';
});
});
// textarea、img 依同樣方式處理
}
每個元件都做了兩件事:一是加上 onfocus="this.blur();return false;",讓元件一取得焦點就立刻失焦,使用者無法點入編輯;二是用一個帶有 setCapture/releaseCapture 的 span 把它包起來,攔截滑鼠操作。由於對各型別元件一視同仁,這段程式能達到「任何元件都唯讀」的效果,很適合用於報表檢視或權限受限的頁面。