smilies to textarea on click(点击时文本区域的表情符号)
问题描述
我有一个小问题
我想点击我的笑脸并将文本插入文本区域.当我以后想添加笑脸时,笑脸应该添加到光标位置而不是文本区域的末尾.
I want to click on my smileys and insert the text to the textarea. and when I want to add a smiley later, the smiley should be added to the cursor position and not at the end in the textarea.
这是我的 html 代码:
<textarea id="description" name="description"></textarea>
<div id="emoticons">
<a href="#" title="Oik="><img alt="Oik=" border="0" src="/images/emoticon-happy.png" /></a>
<a href="#" title="Oig="><img alt="Oig=" border="0" src="/images/emoticon-unhappy.png" /></a>
<a href="#" title="Om8="><img alt="Om8=" border="0" src="/images/emoticon-surprised.png" /></a>
</div>
这是我的 JS 代码:
$('#emoticons a').click(function(){
var smiley = $(this).attr('title');
$('#description').val($('#description').val()+" "+smiley+" ");
});
在这里您可以看到结果(NO WRAP - BODY)http://jsfiddle.net/JVDES/8/
Here you can see the result (NO WRAP - BODY) http://jsfiddle.net/JVDES/8/
我为我的 javascript 代码使用外部 JS 文件...
你知道为什么代码没有在 NO WRAP - HEAD 模式下运行吗?http://jsfiddle.net/JVDES/9/
I use an extern JS file for my javascript-code...
Do you know why the code isn't running in NO WRAP - HEAD mode?
http://jsfiddle.net/JVDES/9/
感谢您的帮助
问候伯恩特
推荐答案
另外,你可以使用这个函数:
Also, you can use something this function:
function ins2pos(str, id) {
var TextArea = document.getElementById(id);
var val = TextArea.value;
var before = val.substring(0, TextArea.selectionStart);
var after = val.substring(TextArea.selectionEnd, val.length);
TextArea.value = before + str + after;
}
对于您的示例,请查看此处.
For your example, look here.
UPD 1:
要将光标设置在指定位置,请使用下一个函数:
To set cursor at specified position, use the next function:
function setCursor(elem, pos) {
if (elem.setSelectionRange) {
elem.focus();
elem.setSelectionRange(pos, pos);
} else if (elem.createTextRange) {
var range = elem.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
我更新了 jsFiddle 上的代码,因此,要查看新示例,请查看这里.
I updated code on jsFiddle, so, to view new example, look here.
这篇关于点击时文本区域的表情符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!