如何基于当前日期动态设置WordPress页面中iFrame的高度
解决方案:多iframe按日期动态设置高度
要实现每个iframe根据自身截止日期自动调整高度,你需要给每个iframe标记专属日期,再通过脚本批量处理,具体步骤如下:
1. 给iframe添加日期标识
给每个需要控制的iframe加上data-end-date属性,存入对应的截止日期,让每个iframe可以独立判断:
<iframe width="694" height="666" frameborder="0" scrolling="no" src="https://docs.google.com/spreadsheets/..." data-end-date="2025-05-21"> </iframe> <iframe width="694" height="666" frameborder="0" scrolling="no" src="https://docs.google.com/spreadsheets/..." data-end-date="2024-10-01"> </iframe>
2. 编写批量处理脚本
通过脚本遍历所有带日期标识的iframe,逐个判断是否过期并设置高度:
// 等DOM加载完成后执行,避免找不到iframe document.addEventListener('DOMContentLoaded', function() { const now = new Date(); // 获取所有带data-end-date属性的iframe const targetIframes = document.querySelectorAll('iframe[data-end-date]'); targetIframes.forEach(iframe => { // 取出当前iframe的截止日期 const endDate = new Date(iframe.dataset.endDate); // 判断是否过期,设置对应高度 if (endDate - now <= 0) { iframe.style.height = '0px'; // 可选:彻底隐藏残留样式 iframe.style.border = 'none'; iframe.style.scrolling = 'no'; } else { iframe.style.height = '666px'; } }); });
关键说明
- 用
data-*自定义属性绑定每个iframe的专属日期,解决多个iframe无法区分的问题。 - 直接操作DOM元素的
style.height属性,比修改HTML的height属性更直接有效,因为脚本运行时DOM已加载。 - 包裹在
DOMContentLoaded事件里,确保脚本执行时iframe已经被渲染到页面中,避免找不到元素的情况。
内容的提问来源于stack exchange,提问作者Lauren Quantrell
相关产品推荐
相关产品推荐

