嵌套Dynamic Loading of Elements冲突问题:如何实现无冲突加载
问题描述
- 实现屏幕Loading效果时,嵌套场景下出现异常:先点击「loading main」按钮,再点击「loading upload image」按钮,两个Loading显示冲突。
- 曾尝试使用直接子选择器
> .webAppModal__loading,但未正确获取目标元素自身的Loading,导致无法实现独立显示。
问题分析
原代码中使用querySelector(".webApp-shopDefaultModalLoading")会匹配目标元素所有后代中的Loading元素,而非仅目标元素自身的直接子Loading。在嵌套结构中,这会导致误操作父元素的Loading,或重复创建不必要的元素。需要改为匹配目标元素的直接子元素中的Loading,确保每个元素的Loading独立可控。
修复后的完整代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="https://minecart.com.br/assets/js/jquery.min.js?v=2.0.64"></script> <style> .webAppModal__loading{ position: absolute; background: rgba(255, 255, 255, .8); text-align: left; top: 0px; left: 0px; width: 100%; height: 100%; border-radius: 5px; z-index: 5; display: none; } .webAppModal__loading img { position: relative; width: 120px; top: 50%; left: 50%; transform: translate(-50%, -50%); } </style> </head> <body style="padding: 0;margin:0px;"> <button onclick="showLoading('#main');">loading main</button> <button onclick="showLoading('#upload');">loading upload image</button> <div id="main" style="background: red;height:100vh;position:relative;"> <div id="upload" style="background: blue;width:300px;height:300px;position:relative;"> this upload image :D </div> <div> other content </div> </div> <script> function fadeIn(el, duration = 300, callback = "") { $(el).fadeIn(duration, function() { // 替换原判断,避免依赖未定义的swpanel对象 if (typeof callback === "function") { callback(); } }); } function showLoading(element, time = 450) { let $element = (typeof element === "string") ? document.querySelector(element) : element; // 使用直接子元素选择器,仅匹配当前元素的直接子Loading let directLoading = $element.querySelector("> .webApp-shopDefaultModalLoading"); if (directLoading) { fadeIn(directLoading, time); } else { directLoading = $element.querySelector("> .webAppModal__loading"); if (directLoading) { fadeIn(directLoading, time); } else { let _div = document.createElement("div"); let _image = document.createElement("img"); _image.src = `https://minecart.com.br/assets/img/loading.gif`; _div.setAttribute("class", "webApp-shopDefaultModalLoading webAppModal__loading"); _div.appendChild(_image); $element.appendChild(_div); showLoading(element); } } } </script> </body> </html>
关键修改说明
- 选择器调整:将原
querySelector(".xxx")改为querySelector("> .xxx"),仅匹配目标元素的直接子元素,确保每个Loading归属于对应的父元素,避免嵌套时的干扰。 - 修复函数判断:原代码中依赖未定义的
swpanel.functions.is_function,替换为标准的typeof callback === "function"判断,避免报错。 - 逻辑优化:将重复的
querySelector调用提取为变量,提升代码可读性和执行效率。
内容的提问来源于stack exchange,提问作者SnowRunescape
相关产品推荐
相关产品推荐

