How to add style attribute to an image added with getDoc().createElement( “img” ); in TinyMCE

我的梦境 提交于 2019-12-24 16:16:24

问题


How To insert an image at cursor position in tinymce

From the above mentioned question I manage to add an Image in TinyMCE.

var ed = tinyMCE.get('txt_area_id');                // get editor instance
var range = ed.selection.getRng();                  // get range
var newNode = ed.getDoc().createElement ( "img" );  // create img node
newNode.src="sample.jpg";                           // add src attribute
range.insertNode(newNode);                          // insert Node

I am trying to add the width to newNode with this code:

 newNode.style = "width:600px;"; // not working

but its not working, same goes for class I cannot add a class via this code:

newNode.class= "myClass"; // this one is also not working

If any one have some idea please let me know thanks.


回答1:


The problem is here:

newNode.style = "width:600px;";

You're accessing the node's style object, rather than the style attribute. So, you can either update, or set, the style object:

newNode.style.width = "600px;";

Or update, or set, the style attribute:

newNode.setAttribute("style", "width:600px");

Note that, in the latter example, any existing values held in the style attribute will be overwritten with the new string; to update only one property value you should use the former example, and target specific properties of the style object.

To update the classes of an element:

newNode.className = "newClassName";

Or:

newNode.classList.add("newClassName");


来源:https://stackoverflow.com/questions/33960835/how-to-add-style-attribute-to-an-image-added-with-getdoc-createelement-img

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!