JavaScript 如何设置鼠标为等待状态
在JavaScript中,我们可以很容易地将鼠标设置为等待状态。在本文中,我们将看看如何做到这一点。实际上,这是一个非常简单的任务,有一个CSS的cursor属性,它有一些值,其中一个值是 wait 。我们将使用CSS的[cursor:wait]属性,并使用JavaScript控制其行为。
将光标设置为等待状态在许多情况下可能非常有用,例如,如果我们在某个支付交易页面上点击完整支付按钮,然后在按钮被点击后应该将光标设置为等待,以防止在交易完成之前在页面的任何地方进行意外点击。
示例1: 在这个示例中,我们将创建一个按钮,当按钮被点击时,光标将处于等待状态。为此,我们将使用JavaScript的addEventListener()函数。借助这个函数,我们可以控制事件(如点击、悬停等)的行为。
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<Style>
* {
margin: 0px;
padding: 0px;
box-sizing: border-box;
}
.box {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: rgb(36, 36, 36);
}
#btn {
height: 50px;
width: 100px;
border-radius: 10px;
border: none;
outline: none;
background-color: rgb(2, 151, 2);
font-family: Impact, Haettenschweiler,
'Arial Narrow Bold', sans-serif;
font-size: 1.1rem;
}
</Style>
</head>
<body>
<div class="box">
<button id="btn">Click me</button>
</div>
<script>
document.getElementById("btn")
.addEventListener("click", function() {
document.body.style.cursor = "wait";
document.getElementById("btn")
.style.backgroundColor = "gray";
document.getElementById("btn")
.style.cursor = "wait";
});
</script>
</body>
</html>
输出:
示例 2: 对于这个示例,我们将使用相同的JavaScript的 addEventListener() 方法,使用 hover 事件,并指定光标应该停留的位置。在这种情况下,我们创建了两个容器,光标在第一个容器中工作正常,但在第二个容器中,光标将变成等待状态。
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<Style>
body {
margin: 0px;
padding: 0px;
box-sizing: border-box;
}
.box {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: rgb(36, 36, 36);
}
#box1 {
height: 100px;
width: 100px;
border-radius: 50%;
background-color: Green;
}
#box2 {
height: 100px;
width: 100px;
border-radius: 50%;
background-color: rgb(102, 11, 3);
margin: 5px;
cursor: wait;
}
</Style>
</head>
<body>
<div class="box">
<div id="box1"></div>
<div id="box2"></div>
</div>
<script>
document.getElementById("box2")
.addEventListener("hover", function() {
document.getElementById("box2")
.style.cursor = "wait";
});
</script>
</body>
</html>
输出: