【JavaScript】Js控制页面所有元素只读
在页面初始化加载以下readOnlyPage()方法,可实现所有元素只读,方便实用。
<script language="javascript"> function readOnlyPage(){ elements = document.all; for ( var i = 0; i < elements.length; i++) { setReadonlyOfElement(elements[i]); } } function setReadonlyOfElement(iElement){ var elementType = iElement.type; if ((elementType == "hidden") || (elementType == "password") || (elementType == "text") || (elementType == "textarea")){ if(iElement.setReadonlyFlag==true){ return; }else{ iElement.setReadonlyFlag = true; } if(iElement.onblur!=null){ iElement.oldOnblur = iElement.onblur; iElement.onblur = functionDoNothing; } if(iElement.ondblclick!=null){ iElement.oldOndblclick = iElement.ondblclick; iElement.ondblclick = functionDoNothing; } if(iElement.onfocus!=null){ iElement.oldOnfocus = iElement.onfocus; iElement.onfocus = functionDoNothing; } if(iElement.className!=null){ iElement.oldClassName = iElement.className; } iElement.className="readonly"; iElement.readOnly = true; } // 不要把按钮设只读 //else if(elementType=="button"){ // if(iElement.setReadonlyFlag==true){ // return; // }else{ // iElement.setReadonlyFlag = true; // } //} else if(elementType == "checkbox"){ setCheckBoxReadonly(iElement,true); } else if(elementType == "radio"){ setRadioReadonly(iElement,true) }else if(elementType == "select-one"){ if(iElement.setReadonlyFlag==true){ return; }else{ iElement.setReadonlyFlag = true; } var optionTags = new Array(); var index = 0; var optionObj; var elementValue = iElement.value; var tag; var options = iElement.options; if(options.length>1){ for(var j = options.length-1; j >= 0; j--){ tag = new Array(); optionObj=options[j]; tag["value"] = optionObj.value; tag["text"] = optionObj.text; optionTags[index++] = tag; if(tag["value"] != elementValue){ iElement.remove(j); } } } iElement.optionTags = optionTags; //iElement.className="readonly"; } } function setCheckBoxReadonly(field,flag) { if(flag==true) { if(field.setCheckBoxReadonlyFlag!=true) { field.setCheckBoxReadonlyFlag=true; field.oldClassName = field.className; field.oldOnclick = field.onclick; field.className = "readonlycheckbox"; field.onclick = functionReturnFalse; } } else { if(field.setCheckBoxReadonlyFlag==true) { field.className = field.oldClassName; field.onclick = field.oldOnclick; field.setCheckBoxReadonlyFlag = false; } } } function setRadioReadonly(field,flag) { if(flag==true) { if(field.setRadioReadonlyFlag!=true) { field.oldClassName = field.className; field.oldOnfocus = field.onfocus; field.className = "readonlyradio"; field.onfocus = functionCancelFocus; field.disabled = true; } } else { if(field.setRadioReadonlyFlag==true) { field.className = field.oldClassName; field.onfocus = field.oldOnfocus; field.setRadioReadonlyFlag = false; field.disabled = false; } } } </script>