温馨提示:这篇文章已超过239天没有更新,请注意相关的内容是否还可用!
Ajax加载图标效果是一种在网页中使用Ajax技术实现的加载提示效果。当用户点击加载更多按钮时,网页会通过Ajax请求获取更多的数据,并在加载过程中显示一个加载图标,以提醒用户数据正在加载中。
示例代码如下:
<!DOCTYPE html>
<html>
<head>
<title>Ajax加载图标效果</title>
<style>
.loading-icon {
display: none;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 50px;
height: 50px;
background-color: #fff;
border-radius: 50%;
border: 3px solid #ccc;
border-top-color: #333;
animation: spin 1s infinite linear;
}
@keyframes spin {
0% {
transform: translate(-50%, -50%) rotate(0deg);
}
100% {
transform: translate(-50%, -50%) rotate(360deg);
}
}
</style>
</head>
<body>
<div id="content">
<!-- 这里是页面内容 -->
</div>
<button id="loadMoreBtn">加载更多</button>
<div class="81d5-4ad2-d017-f070 loading-icon"></div>
<script>
var loadMoreBtn = document.getElementById('loadMoreBtn');
var loadingIcon = document.querySelector('.loading-icon');
var contentContainer = document.getElementById('content');
loadMoreBtn.addEventListener('click', function() {
showLoadingIcon();
fetchData();
});
function showLoadingIcon() {
loadingIcon.style.display = 'block';
}
function hideLoadingIcon() {
loadingIcon.style.display = 'none';
}
function fetchData() {
// 使用Ajax请求获取更多数据
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com/api/data', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var data = JSON.parse(xhr.responseText);
appendDataToContent(data);
hideLoadingIcon();
}
};
xhr.send();
}
function appendDataToContent(data) {
// 将获取到的数据追加到页面内容中
var dataHtml = '';
data.forEach(function(item) {
dataHtml += '<div>' + item.title + '</div>';
});
contentContainer.innerHTML += dataHtml;
}
</script>
</body>
</html>
以上示例代码中,首先定义了一个加载图标的样式,通过CSS实现了一个旋转的加载图标。然后在页面中添加了一个内容容器和一个加载更多按钮。当用户点击加载更多按钮时,通过addEventListener方法绑定了一个点击事件监听器。在事件处理函数中,首先调用showLoadingIcon函数显示加载图标,然后调用fetchData函数使用Ajax请求获取更多数据。在fetchData函数中,使用XMLHttpRequest对象发送GET请求获取数据,并在请求成功后将数据追加到页面内容中,最后调用hideLoadingIcon函数隐藏加载图标。
这样,当用户点击加载更多按钮时,网页会显示加载图标并通过Ajax请求获取更多数据,数据加载完成后,加载图标会被隐藏,新的数据会被追加到页面内容中。这种方式可以提升用户体验,让用户知道数据正在加载中。