我有一个小问题
我想点击我的表情和插入文本到文本区域。 当我想在以后添加一个笑脸,笑脸应该被添加到光标位置,而不是在textarea的结束。
这是我的html代码:
<textarea id="description" name="description"></textarea>
<div id="emoticons">
<a href="#" title=":)"><img alt=":)" border="0" src="/images/emoticon-happy.png" /></a>
<a href="#" title=":("><img alt=":(" border="0" src="/images/emoticon-unhappy.png" /></a>
<a href="#" title=":o"><img alt=":o" 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/
我使用一个外部JS文件我的JavaScript代码...
你知道为什么代码不能在不循环运行 - HEAD模式? http://jsfiddle.net/JVDES/9/
感谢您的帮助
问候bernte
此外,您还可以使用的东西,这个功能:
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;
}
为了您的例子,看这里 。
UPD 1:
要设置光标在指定位置,请使用下一个函数:
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更新的代码,因此,查看新的例子,看看这里 。
试试这个- http://jsfiddle.net/JVDES/12/
信贷的插入位置的功能去- https://stackoverflow.com/a/1891567/981134
之间的差异no wrap (head)
和no wrap (body)
是,前者将尽快运行代码,并在页面加载后,后者将运行代码。
在这种情况下,与no wrap (head)
,该代码被之前“#emoticons一个”存在运行。 因此$(“#表情一”)返回,并没有不重视的点击处理程序。 后来,创建链接。
因此,解决的办法是告诉代码在页面加载时运行。
有一对夫妇,这样的等价方式。 http://api.jquery.com/ready/
$(document).ready(handler)
$().ready(handler)
(这是不推荐)
$(handler)
因此,使用第3版,我们有:
$(function() {
$('#emoticons a').click(function(){
var smiley = $(this).attr('title');
$('#description').val($('#description').val()+" "+smiley+" ");
});
});
http://jsfiddle.net/Nc67C/
尝试也是这个...
$('#emoticons a').click(function() {
var smiley = $(this).attr('title');
var cursorIndex = $('#description').attr("selectionStart");
var lStr = $('#description').val().substr(0,cursorIndex);
var rStr = $('#description').val().substr(cursorIndex);
$('#description').val(lStr+" "+smiley+" "+rStr);
});
您的评论后修复:
$('#emoticons a').click(
function(){var smiley = $(this).attr('title');
var cursorIndex = $('#description').attr("selectionStart");
var lStr = $('#description').val().substr(0,cursorIndex) + " " + smiley + " ";
var rStr = $('#description').val().substr(cursorIndex);
$('#description').val(lStr+rStr);
$('#description').attr("selectionStart",lStr.length);
});