我正在尝试编写文本区域之类的程序,仅用于培训。
我有一个包含(用户生成的)文本的 div:
<div id="editor">Hello! I am a Text!</div>
例如,如果我在“Hello”的两个“L”之间单击(用鼠标左键),我想看到这个:
<div id="editor">Hel<div id="cursor">|</div>lo! I am a Text!</div>
我如何实现这一目标?直到现在,我一直在用...
//HTML
<div id="editor" onclick="setCursorWithMouse()"><!-- User-Text --></div>
//jQuery
function setCursorWithMouse(){
$('#editor').append('<div id="cursor">|</div>');
}
...但是,当然,它只是将光标添加到 div 的末尾。
我如何知道用户点击的确切位置、将光标(或其他)添加到哪里、将文本拆分到哪里?
谢谢
编辑:
我不想使用 contenteditable!就这样看吧:我想在鼠标点击的位置拆分一个字符串。
我知道 .append() 不是我要找的! .append() 只是稍后更好的函数的占位符。我现在要求的这个功能。
我使用固定宽度的字体。
最佳答案
这是我能得到的最接近的: DEMO
var clicked=false;
$('#editor').click(function(e){
$(this).addClass('active');
var letterWidth=7;
$('#editor span').remove();
var clickPos=e.pageX-$(this).offset().left;
if(!clicked) clickPos+letterWidth;
var letter=Math.round(clickPos/letterWidth);
var before=$(this).html().substr(0,letter);
var after=$(this).html().substr(letter,$(this).html().length);
$(this).html(before+'<span>|</span>'+after);
clicked=true;
});
$(document).click(function(e){
if(!$('#editor').is(e.target)){
$('#editor').removeClass('active');
$('#editor span').remove();
clicked=false;
}
});
我希望它足够接近! :)
注意:
这段代码假设font-size
是16px
!
恐怕您必须计算font-size
才能进一步扩展。
关于javascript - jQuery:在鼠标单击位置拆分文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25701097/