首先说一下readonly属性的应用场景ide
这里要说一下disabled和readonly的不一样,若是一个输入项的disabled设为true,则该表单输入项不能获取焦点,用户的全部操做(鼠标点击和键盘输入等)对该输入项都无效,最重要的一点是当提交表单时,这个表单输入项将不会被提交。 this
input标签须要readonly效果的,一般是type=text/checkbox/radio,下面一一介绍这三种类型的readonly效果实现。spa
<!-- input标签type=text的readonly效果实现 --> <input type="text" readonly="readonly" value="readonly" />
<!-- input标签type=checkbox的readonly效果实现 --> <input type="checkbox" name="checkbox1" value="checkbox1" id="red" checked="checked" /> <label for="red">红色</label> <input type="checkbox" name="checkbox2" value="checkbox2" id="color" /> <label for="color">颜色</label> <script> //JS实现readonly效果 $('input[type="checkbox"]').bind("click", function(){ this.checked = !this.checked; }); </script>
<!-- input标签type=radio的readonly效果实现 --> <input type="radio" name="radio" value="radio1" id="red" checked="checked" /> <label for="red">红色</label> <input type="radio" name="radio" value="radio2" id="blue" /> <label for="blue">蓝色</label> <script> //JS实现readonly效果 $('input[type="radio"]').each(function(){ if($(this).attr("checked") != "checked"){ $(this).attr("disabled", true); } }); </script>
<!-- textarea标签的readonly效果实现 --> <textarea readonly="readonly">不可编辑</textarea>
<!-- select标签readonly效果实现 --> <select name="readonly"> <option value="red" selected="selected">red</option> <option value="green">green</option> <option value="blue">blue</option> </select> <script> //JS实现readonly效果 $('select').focus(function(){ this.defaultIndex = this.selectedIndex; }); $('select').change(function(){ this.selectedIndex = this.defaultIndex; }); </script>
若是值是固定的话,传输参数也能够经过设置隐藏域实现,让本来显示的disabled为true就行,如:code
<!-- 设置隐藏域,传输数据 --> <input type="hidden" name="hide" value="hide" /> <input type="text" name="hide" value="hide" disabled="disabled">
readonly的展现效果没disabled好,disabled让用户知道这是不可编辑的,而readonly会给用户一种错觉。orm