基于iframe高度隐藏Div:动态尺寸变化无实时更新问题
Hey there! The issue with your current code is that it only checks the height once when the page finishes loading—so if the iframe's height changes later (like when its content loads dynamically), it won't trigger the show/hide logic again. Here are a few solid solutions to fix this:
Solution 1: Use ResizeObserver (Modern, Efficient)
The ResizeObserver API lets you listen for real-time changes to an element's size, making it ideal for this scenario:
jQuery(document).ready(function($){ // Reusable function to handle the show/hide logic function toggleExecPhp() { if ($(".remove-text").height() <= 582) { $("#execphp-31").hide(); } else { $("#execphp-31").show(); } } // Run once when the page loads toggleExecPhp(); // Set up the observer to watch the target element const targetElement = document.querySelector(".remove-text"); const resizeObserver = new ResizeObserver(toggleExecPhp); resizeObserver.observe(targetElement); });
Note: This works best if the .remove-text element's height changes directly. If it's an iframe whose content updates but the iframe's own height doesn't auto-adjust, you'll need to first sync the iframe's height to its content, or use the next solution.
Solution 2: Monitor Iframe Content Height (Same-Origin Only)
If .remove-text is an iframe hosted on the same domain as your page, you can directly listen for resize events inside its content:
jQuery(document).ready(function($){ function toggleExecPhp() { const iframe = $(".remove-text")[0]; // Get the actual height of the iframe's content const contentHeight = iframe.contentDocument.body.scrollHeight; if (contentHeight <= 582) { $("#execphp-31").hide(); } else { $("#execphp-31").show(); } } // Run once on initial load toggleExecPhp(); // Listen for resize events inside the iframe const iframe = $(".remove-text")[0]; iframe.contentWindow.addEventListener("resize", toggleExecPhp); // Also trigger when the iframe finishes loading its content iframe.addEventListener("load", toggleExecPhp); });
Important: This only works if the iframe's content shares the same origin (domain, protocol, port) as your main page—browser security rules block cross-origin access to iframe content.
Solution 3: Periodic Height Check (Fallback for Cross-Origin)
If you're dealing with a cross-origin iframe and can't access its content, a periodic check is a reliable fallback. It checks the height at regular intervals:
jQuery(document).ready(function($){ function toggleExecPhp() { if ($(".remove-text").height() <= 582) { $("#execphp-31").hide(); } else { $("#execphp-31").show(); } } // Run once on page load toggleExecPhp(); // Check every 500ms (adjust this value based on your needs) setInterval(toggleExecPhp, 500); });
Tweak the interval time (500ms) to balance responsiveness and resource usage—shorter intervals react faster but use slightly more browser resources.
内容的提问来源于stack exchange,提问作者iTsHutchy

