[英]append an image tag inside content editable div at cursor position
I have a contentEditable
div and a list of emojies
images. 我有一个
contentEditable
div和一个emojies
图像列表。 What I am trying to do is that when a user click on an image, the image tag should be inserted at the cursor position. 我正在尝试做的是,当用户单击图像时,应将图像标签插入光标位置。
I tired to do this but this code only insert the image at the end of the div which is not the case for me 我很累这样做,但是这段代码只将图像插入div的末尾,对我来说不是这种情况
$("#editable").append($(this).id); // $(this) is the image tag
How can I fix my problem? 我该如何解决我的问题? jsfiddle : http://jsfiddle.net/7VNTn/
jsfiddle: http : //jsfiddle.net/7VNTn/
try this code , change "IMAGE URL" with any image url 试试这个代码,用任何图像URL更改“ IMAGE URL”
var image = '<p><img src="IMAGE URL" ></p>';
var sel, range, node;
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = window.getSelection().getRangeAt(0);
node = range.createContextualFragment(image);
range.insertNode(node);
}
} else if (document.selection && document.selection.createRange) {
document.selection.createRange().pasteHTML(image);
}
Use following code. 使用以下代码。
$("#editable").html($(this).id);
append method adds the element after your editable tag.So html method will put image inside youe row.try this append方法将元素添加到可编辑标签的后面。因此html方法会将图像放在行中。
Try this code 试试这个代码
$(document).ready(function(){
$("#image1").click(function(){
$("#editable").prepend($(this));
});
});
I used prepend instead of append since you want the image to appear before the text. 我使用前置而不是追加,因为您希望图像出现在文本之前。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.