我正在尝试在 Google 应用程序脚本中创建一个进度条,当有人单击按钮(Go)时,它会自动缓慢地从开始到结束。您在 Firefox 下载窗口中看到的内容。 这是我的代码。
function doGet(e) {
var app = UiApp.createApplication();
var progressPanel = app.loadComponent("progressbar_auto");
var gobutton =app.getElementById("go_btn");
var go_btn_handler =app.createServerHandler("updateProgressbar");
go_btn_handler.addCallbackElement(gobutton);
gobutton.addClickHandler(go_btn_handler)
app.add(progressPanel);
return app;
}
//function time(i){
// Utilities.sleep(5);
// }
function updateProgressbar(){
var app = UiApp.getActiveApplication()
for(var i =1 ; i < 250 ; i++ ){
app.getElementById("progress").setWidth(i + 'px');
time();
}
Logger.log(i);
return app;
}
但是根据这段代码for循环会执行得非常快&,进度条完成得很快。有什么办法可以减缓这个速度吗?
您可以在这里找到我的申请。
有没有办法添加一个滑动条,来控制进度条。我们可以在 php 或 HTML 5 中做一些事情。
谢谢
为什么不使用 HtmlServices 来实现这一点。去尝试一下: 点击这里
你可以使用jquery来实现这个。
更新答案:要获取服务器端运行的脚本的状态,您需要将进度存储到缓存中。然后客户端可以调用服务器端函数来检索它。 https://developers.google.com/apps-script/reference/cache/cache-service
我制定了一个解决方案,按照Greg的建议,将数据存储在服务器端的缓存中并读取客户端的缓存。
服务器端缓存进度数据
var cache = CacheService.getScriptCache();
async function updateCacheProgress(current, total, student) {
// cache for 10 seconds
cache.put("total", total, 10);
cache.put("current", current, 10);
cache.put("student", student, 10);
}
客户端脚本
window.addEventListener('load', getUpdatedProcess);
function updateProgress(data) {
console.log('#student: ' + data.student)
console.log('#current: ' + data.current)
console.log('#total: ' + data.total)
var ProgressBar = document.getElementById('progressBar');
var Progress = document.getElementById('progress');
var ProgressStatus = document.getElementById('progressStatus');
var percent = 0.1
percent = data.current / data.total *100;
percent = percent.toFixed(1);
Progress.style.width = percent + '%';
Progress.innerText = percent + '%';
ProgressStatus.innerHTML = data.student + ` (${data.current} of ${data.total})`
if(percent < 100) getUpdatedProcess()
}
function getUpdatedProcess() {
google.script.run.withSuccessHandler(updateProgress).getProgress();
}
检索通过客户端执行的存储缓存的应用程序脚本
function getProgress() {
var total = cache.get("total");
var current = cache.get("current");
var student = cache.get("student");
return {total: total, current: current, student: student}
}
客户端 HTML
<html>
<head>
<base target="_top">
<style>
* {
font-family: 'Arial';
}
#progressBar {
width: 100%;
background-color: silver;
}
#progress {
width: 0%;
height: 30px;
line-height: 32px;
text-align: center;
color: white;
background-color: green;
}
#progressStatus {
}
</style>
</head>
<body>
<div id="progressBar">
<div id="progress"></div>
</div>
<br><br>
<div id="progressStatus"><?= student ?> (<?= progress ?>)</div>
</body>
</html>
不,没有真正的方法可以在 Apps 脚本上创建进度条。
不过有一些解决方法。您可以向同一个按钮添加多个处理程序,并且在每个处理程序中,通过不同的睡眠时间,您可以多次更新 GUI。或者,像大多数人一样,在客户端处理程序中显示无尽的进度 gif 动画(用于即时反馈),并在第二个处理程序完成后,在您实际执行工作的 ServerHandler 中隐藏图像并返回结果。