input标签的属性:
disabled:表单项禁用,不可修改值,也不会被提交
readonly:表单项只读,不可修改值,但会被提交
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <!--显示获取的1值 并且 设置input权限为只读--> <input type="button" value="只读/可写" onclick="autoGain()"> <!--作用框,用于实现效果--> <input type="text" name="wzwName" readonly="readonly"> </body> <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"> </script> <script type="text/javascript"> // 只读/可写 切换单机事件方法 function autoGain() { // 获取input中的值 var val = $("input[name=‘wzwName‘]").val(); // 如果等于1说明已经设置为只读模式了 if(val == 1) { // 将只读模式删除 $("input[name=‘wzwName‘]").removeAttr("readonly"); }else{ // 添加只读模式到input框中并设置value值为1 $("input[name=‘wzwName‘]").val("1").attr("readonly","readonly"); } } </script> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script> function switchUser() { var usernameEl = document.getElementById("username"); const beforeVal = usernameEl.getAttribute("readonly"); console.log("切换前状态:" + getStatus(beforeVal)); if (beforeVal === null) { usernameEl.setAttribute("readonly", "readonly"); } else { usernameEl.removeAttribute("readonly"); } const afterVal = usernameEl.getAttribute("readonly"); console.log("切换后状态:" + getStatus(afterVal)); } function getStatus(readonlyVal) { if (readonlyVal === null) { return "读写" } else { return "只读" } } </script> </head> <body> 用户名:<input type="text" id="username" name="username"><br> <button onclick="switchUser()">切换用户名readonly属性</button> </body> </html>
js技术之input只读功能可以通过js设置readonly
原文:https://www.cnblogs.com/saoge/p/14875104.html