我正在尝试实施一个用户可以输入文字/图片的评论框。就像我们使用Gmail一样,打开文本框,在其中键入或拖动图像。这是如何完成的?它有什么用?这种文本和图像的混合如何转换并用$ .ajax()包装到XMLHttp请求中?或者我过度简化了问题,人们这样做的方式比我知道的要复杂得多?
如果有人可以向我展示一段示例代码或指向处理此问题的现有javascript库,我们将不胜感激。谢谢!
答案 0 :(得分:1)
这就是我在评论中描述的内容:
// Get reference to div, img and button
var d = document.getElementById("div1");
var i = document.getElementById("drag1");
var btn = document.getElementById("save");
// Wire image drag event handler
i.addEventListener("dragstart", drag);
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
function allowDrop(ev) {
ev.preventDefault();
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
// Wire up the save button
btn.addEventListener("click", function(evt){
// First, turn off contenteditable
div1.removeAttribute("contenteditable");
// Now, get entire contents of div
var updatedContents = div1.innerHTML;
// If you want to save the contents, you'd have to persist them somewhere
// but, all you have to save is the string: "updatedContents"
console.log(updatedContents);
});
#div1 {
width: 100px;
height: 100px;
padding: 10px;
border: 1px solid #aaaaaa;
}
img { width:50px; }
<p>Drag the image into the rectangle and type:</p>
<img id="drag1" src="https://s-media-cache-ak0.pinimg.com/736x/9a/26/84/9a2684c4213171476e13732af3b26537.jpg" draggable="true">
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)" contenteditable></div>
<button id='save'>Save</button>