如何在现有jQuery代码中添加图示的搜索结果加载效果
搜索加载骨架屏实现方案
你不需要调整现有$.get的请求逻辑,这套实现完全兼容Drupal behaviors机制,和你截图里的闪光占位加载效果一致,分两步接入即可:
- 先添加骨架屏的CSS样式,可以放到主题自定义样式表中:
.search-loading-wrap { padding: 1rem 0; } .skeleton-line { height: 16px; margin-bottom: 12px; border-radius: 4px; background: linear-gradient(90deg, #f2f2f2 25%, #e6e6e6 50%, #f2f2f2 75%); background-size: 200% 100%; animation: skeletonBlink 1.4s ease-in-out infinite; } .skeleton-line:nth-of-type(1) { width: 78%; } .skeleton-line:nth-of-type(2) { width: 100%; } .skeleton-line:nth-of-type(3) { width: 62%; } @keyframes skeletonBlink { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }
- 修改现有jQuery代码,把原来写死的
'searching'文本替换为骨架屏HTML结构,接口返回数据后会自动覆盖加载态内容:
$('#popup-search-input').on('keypress', function (e) { if (e.which === 13) { // 插入加载骨架结构 const loadingTpl = ` <div class="search-loading-wrap"> <div class="skeleton-line"></div> <div class="skeleton-line"></div> <div class="skeleton-line"></div> </div> `; $('.search-results').html(loadingTpl); $.get('/api/entity-product-search/' + $(this).val(), function (data) { $('.search-results').html(data); }); } });
可选优化
- 你可以自行调整
.skeleton-line的高度、宽度比例、颜色、间距参数,匹配你站点搜索结果的实际排版 - 如果需要处理请求异常场景,可以加失败回调,避免加载态一直停留:
$.get('/api/entity-product-search/' + $(this).val(), function (data) { $('.search-results').html(data); }).fail(function () { $('.search-results').html('<p>搜索失败,请检查网络后重试</p>'); });
- 这套实现无任何第三方依赖,不会和Drupal的jQuery版本、Behaviors注册逻辑产生冲突。
内容的提问来源于stack exchange,提问作者nathan111777
相关产品推荐
相关产品推荐

