![](/img/trans.png)
[英]Create a general javascript or jquery to make a div or tag set focus on first input inside of it when the div or tag clicked
[英]Set focus to the end of input tag by javascript
敬禮 我對javascript有一些問題。
我制作了翻譯腳本,該腳本允許格魯吉亞用戶通過拉丁字母鍵入格魯吉亞。 因此,當我在input標簽上進行操作時,無法將焦點設置到文本的末尾..正確地,光標位於文本的末尾,但是如果文本比input標簽大得多,則它必須自動滾動並且不能隱藏。
這是代碼。
$(document).ready(function() {
$(".geok").geokbd();
});
$.fn.geokbd = function() {
symbols = "abgdevzTiklmnopJrstufqRySCcZwWxjh";
this.relatedCheckbox = $("<input type=\"checkbox\" name=\"geokbd\" />").attr('checked', true);
$(this).after(this.relatedCheckbox);
$(this).keypress(
function(e) {
if ((e.charCode) == 96) {
if ($(this).next('input').attr('checked')) {
$(this).next('input').attr('checked', false);
} else {
$(this).next('input').attr('checked', true);
}
return false;
}
if ($(this).next('input').attr('checked')) {
if ((index = symbols.indexOf(String.fromCharCode(e.charCode))) >= 0) {
ret = String.fromCharCode(index + 4304);
this.focus();
var scrollTop = this.scrollTop,
start = this.selectionStart,
end = this.selectionEnd;
var value = this.value.substring(0, start) + ret + this.value.substring(end,this.value.length);
this.value = value;
this.scrollTop = scrollTop;
this.selectionStart = this.selectionEnd = start + ret.length;
return false;
}
}
}
);
}
謝謝
有幾個很好的答案
例如,您可以使用
<input id="search" type="text" value="mycurrtext" size="30"
onfocus="this.value = this.value;" name="search"/>
或者,您可以使用JQuery插件:PutCursorAtEnd。 作者甚至在此處發布了源代碼,我測試了它對於Opera的有效性。
獲取最后一個輸入標簽的id
並用該ID替換name
,以下是基本邏輯
<script type="text/javascript">
function setFocus()
{
document.getElementById("name").focus();
}
</script>
</head>
<body onload="setFocus()">
<form>
Name: <input type="text" id="name" size="30"><br />
Surname: <input type="text" id="surname" size="30">
</form>
</body>
您是否嘗試過這個:
function doSetCaretPosition (oField, iCaretPos) {
// IE Support
if (document.selection) {
// Set focus on the element
oField.focus ();
// Create empty selection range
var oSel = document.selection.createRange();
// Move selection start and end to 0 position
oSel.moveStart ('character', -oField.value.length);
// Move selection start and end to desired position
oSel.moveStart ('character', iCaretPos);
oSel.moveEnd ('character', 0);
oSel.select ();
}
// Firefox support
else if (oField.selectionStart || oField.selectionStart == '0') {
oField.selectionStart = iCaretPos;
oField.selectionEnd = iCaretPos;
oField.focus ();
}
}
$(document).ready(function() {
$("#yourElement").focus();
doSetCaretPosition(document.getElementById("yourElement"),999);
});
(來源: http : //www.webdeveloper.com/forum/archive/index.php/t-74982.html )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.