首先,我的 html 中有一个图像,我在 windown.onload 中添加了 dblclick 事件来切换类,它工作正常。
//html
<button onclick="insertImageImageFromLink('../pic02.png')" >
Add New Image
</button>
<div contenteditable="true">
<img src="../pic01.png" />
</div>
//css
button{
width: 100px;
height: 50px;
}
img {
border:5px solid white;
}
.ontap-2{border-color:green;}
//javascript
function toggleClass(elem, name) {
if (elem.className.indexOf(name) < 0) {
elem.className += ' '+name;
} else {
elem.className = elem.className.split(name).join('');
}
}
function clearSelection() {
var selection =
window.getSelection ? window.getSelection() :
document.getSelection ? document.getSelection() :
document.selection;
if (selection && selection.removeAllRanges) {
// W3C-style
selection.removeAllRanges();
} else if (selection && selection.empty) {
// IE-style
selection.empty();
}
}
function setupEventForAnImage(image) {
image.ondblclick=function(){
toggleClass(image,'ontap-2');
clearSelection();
};
}
function prepareEventHandlers() {
var imageArray = document.getElementsByTagName('img');
for (var i = 0; i < imageArray.length; i++) {
var image = document.getElementsByTagName('img')[i];
setupEventForAnImage(image);
}
}
window.onload = function() {
// prep anything we need to
prepareEventHandlers();
};
现在,我需要从按钮将图像添加到 contenteditable div
<button onclick="insertImageImageFromLink('../pic02.png')" >
function insertNodeAtCursor(node) {
var range, html;
if (window.getSelection && window.getSelection().getRangeAt) {
range = window.getSelection().getRangeAt(0);
range.insertNode(node);
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
html = (node.nodeType == 3) ? node.data : node.outerHTML;
range.pasteHTML(html);
}
}
function insertImageImageFromLink(imageLink){
var imge = new Image();
imge.src = imageLink;
insertNodeAtCursor(imge);
setupEventForAnImage(image);
}
在我的浏览器上插入图像工作,但 setupEventForAnImage(image); 不起作用 像这样的代码: http: //jsfiddle.net/DSa7a/4/但功能插入图像仅在我的浏览器中有效,不适用于此链接。
如果从链接插入事件,如何将事件添加到图像?
请帮忙!谢谢!