jQuery - 单击链接时将光标置于输入字段中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7944098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery - Place cursor in input field when link clicked
提问by skolind
I would like to place the cursor in an input field after a specific link is clicked. I'm using this for a small search engine.
单击特定链接后,我想将光标放在输入字段中。我将它用于小型搜索引擎。
Imagine an input field: []. Then some links which is adding a string like: Denmark, England etc. to the input field.
想象一个输入字段:[]。然后是一些向输入字段添加字符串的链接,例如:丹麦、英格兰等。
Now I need the cursor to be placed like this: "Denmark, [here]".
现在我需要像这样放置光标:“丹麦,[这里]”。
Is this possible?
这可能吗?
* UPDATE *
* 更新 *
I'm using this code right now to replace the text, how would you add the "position cursor"-trick with this?
我现在正在使用此代码来替换文本,您将如何添加“位置光标”技巧?
$('#denmark').click(function(){
$('#searchBoxBig').val('Denmark, ');
});
回答by Nicolas Modrzyk
yes, catch the click event on the anchor prevent the default action and focus on the field.
是的,捕获锚点上的点击事件可防止默认操作并专注于该字段。
the function context contains the element that has been clicked so u can compute which field to apply the focus call on.
函数上下文包含已被单击的元素,因此您可以计算将焦点调用应用于哪个字段。
$(anchorSelector).live("click", function(e) {
e.preventDefault();
$(fieldSelector).focus();
return false;
});
回答by anonymous coward
You can set where the cursor is in an input box with the selectionStart
and selectionEnd
properties. If you don't want any text to be selected, just make them equal to each other.
您可以使用selectionStart
和selectionEnd
属性设置光标在输入框中的位置。如果您不想选择任何文本,只需使它们彼此相等即可。
Here's how you might do it:
您可以这样做:
var input = $("input");
input[0].selectionStart = input[0].selectionEnd = input.val().length;
回答by Ariel
$(":input[name=xxxx]").focus();
Ah, you need the cursor to be after all the text? Take a look here: jQuery Set Cursor Position in Text Areait works the same for an input instead of a textarea.
啊,你需要光标在所有文本之后?看看这里:jQuery Set Cursor Position in Text Area它对于输入而不是 textarea 的工作方式相同。
This also works if you use other selectors.
如果您使用其他选择器,这也适用。