我想用编程的方式设计一个带有背景色的段落,以形成一个“代码区域”,就像在Stackoverflow中的段落周围使用三重引号时一样,或者类似于这个问题。我尝试在这个问题中调整脚本和文档,但是尽管背景颜色发生了变化,但它只在选定的文本部分进行,而不是整个段落占用整个页面的宽度。
建议的解决方法是创建一个Table
,但我不想这样做。
我知道这是可能的,因为您可以手动选择一个段落,然后转到Format > Paragraph styles > Borders and shading
,从那里更改背景色,它会做我想做的任何事情。
我所做的,只将颜色应用于有限的部分(检查element
是Paragraph
的一个实例):
const selection = DocumentApp.getActiveDocument().getSelection();
const rangeElements = selection.getRangeElements();
const element = rangeElements[0].getElement();
element.setBackgroundColor('#D0FAF0');
我怎么做我想做的?有可能吗?
发布于 2019-03-16 07:34:01
如果我的理解是正确的,那么这个示例脚本如何?不幸的是,在当前阶段,还没有修改Document中段落的阴影颜色的方法。我认为这可以通过将来的更新文件服务来实现。但作为目前的解决办法,我认为最近发布的Google可能可以用来实现这一目标。所以我对此提出质疑。
In命令使用以下示例脚本,在运行脚本之前,请在API上启用Google,如下所示。
示例脚本的流程如下所示。
示例脚本用于带有Google文档的容器绑定脚本。请将以下脚本复制并粘贴到脚本编辑器中,<#>please在运行 myFunction()
<#>after Google上选择一个文本。
function myFunction() {
var color = "#D0FAF0"; // Please set a color with hex.
var doc = DocumentApp.getActiveDocument();
var selection = doc.getSelection();
if (selection) {
var hex2rgb = function(hex) {
var str = hex[0] === "#" ? hex.slice(1) : hex;
var rgb = str.split(/(.{2})/).reduce(function(ar, e) {
if (e) ar.push(Math.round(1000 * parseInt(e, 16) / 255) / 1000);
return ar;
}, []);
return {red: rgb[0], green: rgb[1], blue: rgb[2]};
}(color);
var body = doc.getBody();
var id = doc.getId();
var baseUrl = "https://docs.googleapis.com/v1/documents/";
var headers = {"Authorization": "Bearer " + ScriptApp.getOAuthToken()};
var params = {headers: headers};
// Retrieve all contents from Google Document.
var res = UrlFetchApp.fetch(baseUrl + id + "?fields=*", params);
var obj = JSON.parse(res.getContentText());
// Retrieve selected content.
var rangeElements = selection.getRangeElements();
var selectedContents = rangeElements.reduce(function(ar, e) {
var p = e.getElement();
if (p.getType() == DocumentApp.ElementType.TEXT) p = p.getParent();
if (p.getType() == DocumentApp.ElementType.PARAGRAPH || p.getType() == DocumentApp.ElementType.LIST_ITEM) ar.push(obj.body.content[body.getChildIndex(p) + 1]);
return ar;
}, []);
// Modify shading of selected content.
if (selectedContents.length > 0) {
var range = selectedContents.length == 1 ? {startIndex: selectedContents[0].startIndex, endIndex: selectedContents[0].endIndex} : {startIndex: selectedContents[0].startIndex, endIndex: selectedContents[selectedContents.length - 1].endIndex};
var resource = {requests: [{updateParagraphStyle: {
paragraphStyle: {shading: {backgroundColor: {color: {rgbColor: hex2rgb}}}},
range: range,
fields: "shading.backgroundColor",
}}]};
params.method = "post";
params.contentType = "application/json";
params.payload = JSON.stringify(resource);
UrlFetchApp.fetch(baseUrl + id + ":batchUpdate", params);
}
}
}
#39b966
作为颜色。如果我误解了你的问题,而这个解决办法不是你想要的,我道歉。
https://webapps.stackexchange.com/questions/126354
复制相似问题