运行代码时如何使鼠标处于"Wait"模式



我有一个JavaScript函数,它将调用从REST API获取数据,然后过滤数据并显示到表中。

整个过程需要一些时间,所以我想让鼠标处于";等待";模式(在旧Windows中显示为沙漏(,让用户知道进程仍在运行。

然而,我已经尝试了我在网上找到的所有方法,仍然不能让鼠标变成一个"等待";模式鼠标只是一种手动模式(当鼠标悬停在搜索按钮上时(,直到过程结束。我尝试过的代码如下:

// Simply set mouse to "Wait"
const waitMouse = function(){
$('html, body').css("cursor", "wait");
}
// This function will be do most of the process
const SearchData = function(){
// Call Rest API
// Filter data
// Set to JSON array that map to the displayed table
$('html, body').css("cursor", "auto"); //If delete this line, the mouse will change to "Wait" mode after the process finish
}
// This function will be do most of the process
const SearchData2 = asyn() => {
// Call Rest API
// Filter data
// Set to JSON array that map to the displayed table
$('html, body').css("cursor", "auto"); //If delete this line, the mouse will stay in "Wait" mode
}
// This function will be called when click search button
function Run(){
// I did not use all methods below in one go, only 1 method each time
//Try 1 - Simply call the function
$('html, body').css("cursor", "wait");
SearchData();
//Try 2.1 - Use setTimeout on main function
$('html, body').css("cursor", "wait");
setTimeout(SearchData(), 1000);
//Try 2.2 - Use setTimeout on both
setTimeout(function(){$('html, body').css("cursor", "wait");}, 500);
setTimeout(functionCall2(), 2000);
//Try 3.1 - Use some fancy function name Promise
Promise.resolve(0).then(() => waitMouse()).then(() => functionCall());
//Try 3.2 - Use Promise in another way
Promise.resolve(0).then(() => waitMouse());
Promise.resolve(1).then(() => functionCall());  
// Try 4 - Use CSS (Delete )
$('body').addClass('wait');
functionCall();
$('body').removeClass('wait');
//Try 5 - Use asyn
$('html, body').css("cursor", "wait");
SearchData2();
}

以上都不起作用。

有人能帮我解决这个问题吗?

在对Promise对象执行异步操作之前,将光标设置为等待。

一旦Promise解决或拒绝,将样式恢复为默认样式。

这里有一个例子:

const longRunningOperation = () => new Promise(
resolve => setTimeout(() => resolve({foo: 'bar'}), 5000)
);
$(document).ready(function(){
const searchBtn$ = $("#searchBtn");
const waitElements$ = $("html, #searchBtn");
const result$ = $("#result");
searchBtn$.on("click", function() {
waitElements$.css("cursor", "wait");

longRunningOperation()
.then(json => result$.text(JSON.stringify(json, null, 4)))
.then(() => waitElements$.css("cursor", "default"))
.catch(() => waitElements$.css("cursor", "default"))
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="searchBtn">Search</button>
<pre id="result"></pre>

最新更新