<div contenteditable="true">
abcde<img src="abc.jp" />fg
</div>
$('div').append('<img src="abc.jpg" />'); //this will append img at end of text
我尝试将图像添加到 div 的位置 6
有什么方法可以在适当的位置附加图像吗?
最佳答案
获取 div
的文本,在指定位置将其拆分并重新连接。然后覆盖div的html:
var a = $.trim($('div').text());
var b = '<img src="https://jsfiddle.net/img/logo.png" />';
var position = 5;
var output = a.substr(0, position) + b + a.substr(position);
$('div').html(output);
注释
我使用 $.trim()
来避免由于空格或换行符导致的错误位置计数
位置设置为 5
因为 .substr()
从 0
关于javascript - jquery append() 在字符串位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40871073/