JavaScript无法添加令人满意的属性

时间:2016-05-30 09:26:59

标签: javascript html contenteditable

JavaScript的:



var insertImage = function(src, alt) {
   var html = '<div contenteditable="false"><img ' + 'src="'+src+'" alt="'+alt+'" onclick="imageClick()" /></div>';
   document.execCommand('insertHTML', false, html);
};
&#13;
&#13;
&#13;

HTML:

&#13;
&#13;
<body>
  <div id="yq_editor_content" style=" width: 100%; height: 100%; -webkit-overflow-scrolling: touch; overflow: hidden; background-color:lightblue;" contenteditable="true">
  </div>
  <div id="yq_editor_footer"></div>
</body>
&#13;
&#13;
&#13;

但在我执行JavaScript函数后,我得到div没有contenteditable的HTML,如下所示:

image

1 个答案:

答案 0 :(得分:0)

我想你想要这样的东西? https://jsfiddle.net/_jserodio/ywe48rwy/

JavaScript,CSS和HTML

  

var insertImage = function(src, alt) {
   var img = '<img ' + 'src="'+src+'" alt="'+alt+'"/>';
   document.querySelector('#yq_editor_content').innerHTML += img;
};

document.querySelector('#insert').addEventListener("click", function() {
    insertImage('http://cdn.sstatic.net/Sites/stackoverflow/img/favicon.ico', 'so');
}, false);
#insert {
  width: 25px;
  heigth: 25px;
  cursor: pointer;
}
<div id="yq_editor_content" style=" width: 100%; height: 100%; -webkit-overflow-scrolling: touch; overflow: hidden; background-color:lightblue;" contenteditable="true">
  Hello, try to edit this!
</div>
<div id="yq_editor_footer">
  <img id ='insert' src="http://icons.iconarchive.com/icons/oxygen-icons.org/oxygen/256/Actions-insert-image-icon.png" alt="insert image icon">
</div>