ruankao/public/static/js/banner.js
2025-07-14 14:55:25 +08:00

84 lines
3.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 优化后的banner.js
(function () {
// 设置innerHTML
function setInnerHTML(el, html) {
if (el) el.innerHTML = html;
}
// AJAX GET请求
function ajaxGet(url, callback, errorCallback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
try {
var res = JSON.parse(xhr.responseText);
callback(res);
} catch (e) {
console.error('JSON解析失败', e);
if (errorCallback) errorCallback(e);
}
} else {
console.error('请求失败', xhr.status);
if (errorCallback) errorCallback(xhr.status);
}
}
};
xhr.send();
}
// 渲染banner
function renderBanner(bannerList) {
var bannerHtml = '';
bannerList.forEach(function (banner) {
bannerHtml += '<div>' +
'<div class="banner-content">' +
'<div class="banner-image">' +
'<img src="' + banner.image + '" alt="' + (banner.title || '') + '">' +
'</div>' +
'<div class="banner-text">' +
'<span class="banner-title">' + (banner.title || '') + '</span>' +
'<span class="banner-desc">' + (banner.desc || '') + '</span>' +
'<a href="' + (banner.url || 'javascript:;') + '" class="banner-slide">' +
'<span class="banner-btn">查看详情</span>' +
'</a>' +
'</div>' +
'</div>' +
'</div>';
});
var carouselItem = document.querySelector('#test10 div[carousel-item]');
setInnerHTML(carouselItem, bannerHtml);
}
// 主流程
ajaxGet('/index/index/bannerlist', function (res) {
// console.log('banner接口返回', res);
if (res && res.code === 1 && Array.isArray(res.banner)) {
renderBanner(res.banner);
// 确保layui和carousel已加载
if (window.layui) {
layui.use(['carousel'], function () {
var carousel = layui.carousel;
carousel.render({
elem: '#test10',
width: '100%',
height: '100vh',
interval: 4000,
anim: 'fade',
autoplay: true,
full: false,
arrow: 'hover'
});
});
} else {
console.error('layui未加载');
}
} else {
console.error('banner数据异常', res);
}
}, function (err) {
console.error('banner数据请求失败', err);
});
})();