如何便捷将JavaScript变量应用到iframe容器的参数与属性中
实现方法
HTML 本身无法直接解析写在标签属性里的 JS 变量,你可以在获取到视口宽高后,通过 JS 动态修改 iframe 的属性即可达成需求,完整可运行代码如下:
<!DOCTYPE html> <html> <head> <title>Web Page Design</title> </head> <body> <script type="text/javascript"> var viewportwidth; var viewportheight; // 原有获取视口宽高逻辑保留 if (typeof window.innerWidth != 'undefined') { viewportwidth = window.innerWidth, viewportheight = window.innerHeight } else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) { viewportwidth = document.documentElement.clientWidth, viewportheight = document.documentElement.clientHeight } else { viewportwidth = document.getElementsByTagName('body')[0].clientWidth, viewportheight = document.getElementsByTagName('body')[0].clientHeight } document.write('<p>Your viewport width is '+viewportwidth+'x'+viewportheight+'</p>'); // 新增修改iframe的逻辑 const fbIframe = document.getElementById('fbIframe'); // 拼接带动态宽高的src地址 const dynamicSrc = `https://www.facebook.com/plugins/page.php?href=https%3A%2F%2Fwww.facebook.com%2Ffacebook&tabs=timeline&width=${viewportwidth}&height=${viewportheight}&small_header=true&dat_adapter_container_width=true&hide_cover=true&show_facepile=false&appId`; // 给iframe赋值属性 fbIframe.src = dynamicSrc; fbIframe.width = viewportwidth; fbIframe.height = viewportheight; // 【可选扩展】窗口大小变化时自动同步iframe尺寸 window.addEventListener('resize', () => { // 重新计算最新视口宽高 let newW = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; let newH = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; // 更新iframe属性 fbIframe.src = `https://www.facebook.com/plugins/page.php?href=https%3A%2F%2Fwww.facebook.com%2Ffacebook&tabs=timeline&width=${newW}&height=${newH}&small_header=true&dat_adapter_container_width=true&hide_cover=true&show_facepile=false&appId`; fbIframe.width = newW; fbIframe.height = newH; }) </script> <!-- 给iframe加id方便JS选中,初始宽高会被JS覆盖,可随便填 --> <iframe id="fbIframe" src="" width="380" height="500" style="border:none;overflow:hidden" scrolling="no" frameborder="0" allowfullscreen="true" allow="autoplay; clipboard-write; encrypted-media; picture-in-picture; web-share" webkitallowfullscreen="true" mozallowfullscreen="true"></iframe> </body> </html>
内容的提问来源于stack exchange,提问作者Scania_16
相关产品推荐
相关产品推荐

