【问题标题】:How can I make only the focused input available?我怎样才能只使重点输入可用?
【发布时间】:2018-02-25 23:47:34
【问题描述】:
我希望始终只启用一个输入。为此,我可以通过添加 disabled 属性来禁用输入,并在点击 jQuery 时删除该属性。像这样:
$('input').on('click', function(){
$(this).prop('disabled', false);
})
input, div{
width: 230px;
height: 20px;
padding: 0;
margin-top: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform" method="GET" action="/mypath">
<input type="text" disabled ><br>
<input type="text" disabled ><br>
<input type="text" disabled >
</form>
不幸的是,点击时没有任何反应。出了什么问题,我该如何解决?
【问题讨论】:
标签:
javascript
jquery
html
css
【解决方案1】:
禁用的元素不会执行鼠标事件。所以你应该间接选择它们。一种方法是在禁用的输入前添加一个元素以模拟单击该元素。这是实现完全跨浏览器兼容性的唯一方法。
注意您应该在click 上隐藏/显示该元素:
$(this).hide().prev("input[disabled]").prop("disabled", false).focus();
在blur:
$(this).prop("disabled", true).next("div").show();
完整版代码:
$('form#myform > div').on('click', function(){
$(this).hide().prev("input[disabled]").prop("disabled", false).focus();
})
$('form#myform > input').on('blur', function(){
$(this).prop("disabled", true).next("div").show();
})
input, div{
width: 230px;
height: 20px;
padding: 0;
margin-top: 5px;
}
div{
/* border: 1px solid red; */
position: absolute;
margin-top: -22px; /* I've used 22 instead of 20 because of input border */
cursor: text;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform" method="GET" action="/mypath">
<input type="text" disabled >
<div></div>
<br>
<input type="text" disabled >
<div></div>
<br>
<input type="text" disabled >
<div></div>
<br>
</form>
【解决方案2】:
您可以使用readonly 而不是disabled,因为disabled 元素没有事件(您可以查看this answer)。
$('input').on('click', function() {
$('input').prop('readonly', true);
$(this).prop('readonly', false);
})
input,
div {
width: 230px;
height: 20px;
padding: 0;
margin-top: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform" method="GET" action="/mypath">
<input type="text" readonly><br>
<input type="text" readonly><br>
<input type="text" readonly>
</form>