
本文旨在提供一种基于 JavaScript,根据页面 Overlay 元素是否显示,动态控制其他 DOM 元素显示与隐藏的实现方法。我们将通过检查特定 CSS 类名是否存在于 Overlay 元素上,来判断其可见性,并根据结果决定是否添加或隐藏目标 DOM 元素。本文提供详细的代码示例和注意事项,帮助开发者理解和应用此技术。
核心思路是使用 JavaScript 获取 Overlay 元素,然后检查其 CSS 类列表中是否包含特定的类名(例如 shown)。如果包含,则表示 Overlay 可见,反之则不可见。根据这个判断结果,我们可以决定是否添加或隐藏其他 DOM 元素。
以下是一个示例代码,展示了如何根据 Overlay 的 shown 类来动态添加按钮:
document.addEventListener('DOMContentLoaded', function() {
function addElement() {
var overlayContainer = document.getElementById("mobile-start-container");
var divOverlay = document.querySelector(".mobile-start-overlay");
if (divOverlay && divOverlay.classList.contains('shown')) {
console.log("Overlay is shown, so don't display the button");
} else {
// Create new Button element
var newButton = document.createElement("button");
// add class to the new Button
newButton.className = "question-btn";
// add SVG tag inside Button
var newSvg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
// add class to svg tag
newSvg.className = "svg-icon";
newSvg.setAttribute("viewBox", "0 0 10 10"); // 设置 viewBox 属性
// fill svg element with my shape
var svgContent = document.createElementNS("http://www.w3.org/2000/svg", 'path');
svgContent.setAttribute("d", "M 0 0 L 10 10");
svgContent.setAttribute("stroke", "#fff");
svgContent.setAttribute("stroke-width", "1");
newSvg.appendChild(svgContent);
// add svg node to created button
newButton.appendChild(newSvg);
// add new button somewhere else in DOM
var currentDiv = document.getElementById('nav-controls');
if (currentDiv) {
document.body.insertBefore(newButton, currentDiv);
} else {
document.body.appendChild(newButton); // 如果 nav-controls 不存在,则添加到 body 底部
}
console.log(newButton);
}
}
addElement();
});代码解释:
通过本文提供的方案,您可以根据页面 Overlay 的状态,动态地控制其他 DOM 元素的显示与隐藏。这种方法可以用于实现各种交互效果,例如在 Overlay 显示时隐藏某些按钮,或者在 Overlay 隐藏时显示其他内容。 关键在于准确地获取 Overlay 元素,并正确地判断其可见性。
以上就是根据页面 Overlay 状态动态显示 DOM 元素的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号