focus()在Chrome中的getUi().showSidebar html中不起作用



我正在使用自定义Menubar函数在Google Sheets中打开一个包含表单的侧边栏。

我希望每当侧边栏打开时,<textarea>都能被聚焦(这样光标就在其中,任何输入都会立即添加到其中(。但是使用focus()是不起作用的。(根据下一行,对其应用样式工作。(

请问我怎样才能做到这一点?非常感谢你的帮助。

注意:它在Chrome(Win 10(中不起作用,但在Firefox中起作用。

function abc() {
var html = 
'<form id="form">' + 
'<textarea id="title"> </textarea> '+ 
'</form> <button>Submit</button> '+
'<script>'+
' document.getElementById("title").focus(); '+ // << NOT WORKING 
' document.getElementById("title").style.outline ="solid 2px red"' +  // << WORKING
' </script>'+
'';
var a = HtmlService.createHtmlOutput(html)
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setTitle('MY-FORM')
SpreadsheetApp.getUi().showSidebar(a); 
}
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('My Functions')
.addItem('Start', 'abc')
.addSeparator()
.addToUi();
}

您必须等待页面加载。

试试这个:

function abc() {
var html ='<form><input type="text" id="title" name="title" /><br /><input type="button" value="Submit" onclick="google.script.run.processForm(this.parentNode);"/></form>';
html+='<script>window.onload=function(){document.getElementById("title").focus();document.getElementById("title").style.outline="solid 2px red";}</script>';
var ui=HtmlService.createHtmlOutput(html);
SpreadsheetApp.getUi().showSidebar(ui); 
}
function processForm(obj) {
console.log(JSON.stringify(obj));
const ss=SpreadsheetApp.getActive();
const sh=ss.getSheetByName('Sheet1');
sh.getRange('A1').setValue(obj.title);
}

您也可以使用文本区域:

function abc() {
var html ='<form><textarea rows="1" cols="15" id="title" name="title"></textarea><br /><input type="button" value="Submit" onclick="google.script.run.processForm(this.parentNode);"/></form>';
html+='<script>window.onload=function(){document.getElementById("title").focus();document.getElementById("title").style.outline="solid 2px red";}</script>';
var ui=HtmlService.createHtmlOutput(html);
SpreadsheetApp.getUi().showSidebar(ui); 
}

尝试添加布尔属性autofocus:

'<textarea id="title" autofocus> </textarea> '

最新更新