我有许多需要重复填写的输入字段,因此我通常用它Tab来浏览表单。
字段具有需要前置的默认后缀值。当我通过鼠标单击将焦点集中在输入上时,它会按预期工作。
但是,当我在输入之间切换时,它会选择所有文本,这在我的情况下是不良行为。
看看这个:
function setCaretPosition(elem, caretPos) {
if (elem == null) return;
if (elem.createTextRange) {
var range = elem.createTextRange();
range.move('character', caretPos);
range.select();
} else if (elem.selectionStart) {
elem.focus();
elem.setSelectionRange(caretPos, caretPos);
} else {
elem.focus();
}
}
$(document).ready(function() {
$('input').focus(function() {
setCaretPosition(this, 0);
});
});Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input1" value=" km/h" />
<input type="text" id="input2" value=" kg" />Run Code Online (Sandbox Code Playgroud)
使用选项卡导航时如何防止文本输入突出显示其内容?
setTimeout我更喜欢不使用(如果可能的话)的答案。
在 Chrome 和 Explorer 上(不适用于 Edge 和 Firefox),只需:
<input type="text" value=" km/h" onfocus="this.setSelectionRange(this.value.length, this.value.length)"/>
<input type="text" value=" kg" onfocus="this.setSelectionRange(this.value.length, this.value.length)"/>Run Code Online (Sandbox Code Playgroud)
在 Firefox 和 Chrome 上(不适用于 Edge 和 Explorer)
jQuery.fn.putCursorAtEnd = function() {
return this.each(function() {
// Cache references
var $el = $(this), el = this;
// Timeout seems to be required for Firefox
setTimeout(function() {
el.setSelectionRange($el.val().length, $el.val().length);
}, 0);
});
};
var searchInput = $("input");
searchInput.on("focus", function() { // could be on any event
searchInput.putCursorAtEnd()
});Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value=" km/h" />
<input type="text" value=" kg" />Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
975 次 |
| 最近记录: |