如何将样式属性添加到使用getDoc()添加的图像.createElement(" img");在TinyMCE

时间:2015-11-27 15:47:00

标签: jquery tinymce-4

How To insert an image at cursor position in tinymce

从上面提到的问题我设法在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

我正在尝试使用以下代码将宽度添加到newNode

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

但它不起作用,同样适用于类我不能通过此代码添加类:

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

如果有人有任何想法,请让我知道谢谢。

1 个答案:

答案 0 :(得分:2)

问题在于:

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

您正在访问节点的样式对象,而不是样式属性。因此,您可以更新或设置样式对象:

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

或者更新或设置样式属性:

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

请注意,在后一个示例中,style属性中保存的任何现有值都将被新字符串覆盖;要仅更新一个属性值,您应使用前一个示例,并定位样式对象的特定属性。

更新元素的类:

newNode.className = "newClassName";

或者:

newNode.classList.add("newClassName");