js原生实现loading
时间: 2023-11-27 11:03:44 浏览: 51
可以使用JavaScript原生的DOM操作来实现loading效果。下面是一个简单的示例代码:
HTML代码:
```
<div id="loading">
<div class="spinner"></div>
</div>
```
CSS代码:
```
#loading {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
background-color: rgba(0, 0, 0, 0.3);
z-index: 9999;
}
.spinner {
width: 40px;
height: 40px;
border-radius: 50%;
border-top: 3px solid #fff;
border-right: 3px solid transparent;
animation: spin 0.8s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
```
JavaScript代码:
```
// 显示loading
function showLoading() {
var loading = document.getElementById('loading');
if (!loading) {
loading = document.createElement('div');
loading.id = 'loading';
loading.innerHTML = '<div class="spinner"></div>';
document.body.appendChild(loading);
}
}
// 隐藏loading
function hideLoading() {
var loading = document.getElementById('loading');
if (loading) {
document.body.removeChild(loading);
}
}
```
调用示例:
```
showLoading(); // 显示loading
// 执行异步操作
setTimeout(function() {
hideLoading(); // 隐藏loading
}, 3000);
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![whl](https://img-home.csdnimg.cn/images/20210720083646.png)