您的代码中有很多基本错误,结果是返回的值listBox
未定义,主要是因为CallBackElement
您的处理程序没有。
除此之外,UI 的构造不正确,因为listBox
没有添加到panel
.
在click
函数中,您可以简化代码,因为变量images[index]
已经是 ablob
并且可以直接插入到文档中。
我的测试脚本是这样的,我更改了源引用以便能够在我这边测试它......不要忘记恢复你的值。
顺便说一句,您还可以通过添加一些样式属性来改进 UI 以使其看起来更好,但我想这是您代码的简化草稿版本......不是吗?
function sideBar(){
var uiInstance = UiApp.createApplication()
.setTitle('WriteWell')
.setWidth(250);
var panel = uiInstance.createVerticalPanel();
uiInstance.add(panel);
var handler = uiInstance.createServerHandler('click').addCallbackElement(panel);
var box = uiInstance.createListBox().setId("select").setName("mySelector");
var images = [1,2,3,4,5];// restore your code here too, this was for test only...
for(var i = 0; i<images.length; i++){
box.addItem(""+i,i);
}
panel.add(box);
panel.add(uiInstance.createButton("Add Icon").addClickHandler(handler));
DocumentApp.getUi().showSidebar(uiInstance);
}
function click(eventInfo){
var uiInstance = UiApp.getActiveApplication();
var index = parseInt(eventInfo.parameter.mySelector);
var id = "1E6yoROb52QjICsEbGVXIBdz8KhdFU_5gimWlJUbu8DI";// this is the ID of a shared document, not your doc.
var imageResource = DocumentApp.openById(id);
var images = imageResource.getBody().getImages();
DocumentApp.getActiveDocument().getCursor().insertInlineImage(images[index]);
}
编辑:我写了一个小脚本来进一步测试我如何管理图像大小和(稍微)改进用户界面......这是你可以测试的代码
function sideBar(){
var uiInstance = UiApp.createApplication()
.setTitle('WriteWell')
.setWidth(250);
var panel = uiInstance.createVerticalPanel().setStyleAttributes({'padding':'25px','background':'#ffffee'}).setHeight('100%').setWidth('100%');
uiInstance.add(panel);
var handler = uiInstance.createServerHandler('click').addCallbackElement(panel);
var box = uiInstance.createListBox().setId("select").setName("mySelector");
var id = "1E6yoROb52QjICsEbGVXIBdz8KhdFU_5gimWlJUbu8DI";// this is the ID of a shared document, not your doc.
var imageResource = DocumentApp.openById(id);
var images = imageResource.getBody().getImages();// I used it to get some images
for(var i = 0; i<images.length; i++){
box.addItem(images[i].getType()+'-'+i,i);
}
panel.add(box);
panel.add(uiInstance.createButton("Add Icon").addClickHandler(handler));
DocumentApp.getUi().showSidebar(uiInstance);
}
function click(eventInfo){
var uiInstance = UiApp.getActiveApplication();
var index = parseInt(eventInfo.parameter.mySelector);
var id = "1E6yoROb52QjICsEbGVXIBdz8KhdFU_5gimWlJUbu8DI";// this is the ID of a shared document, not your doc.
var imageResource = DocumentApp.openById(id);
var images = imageResource.getBody().getImages();
var newImage = DocumentApp.getActiveDocument().getCursor().insertInlineImage(images[index]);
var originalH = newImage.getHeight();
var originalW = newImage.getWidth();
var ratio = originalW/originalH;
newImage.setWidth(100).setHeight(100/ratio);
}