我创建了一个 iframe,并将其作为叠加层添加到页面中。我希望它位于页面的中央。但是,当我在移动设备上浏览非移动优化页面并放大时,iframe 通常会显示在屏幕之外。
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
width = w.innerWidth || e.clientWidth || g.clientWidth;
display_width = 450;
margin = (width-450) / 2;
frame.setAttribute('style','z-index: 2147483647;position:fixed;top:20px;left:'+margin+'px;width:'+display_width+'px;margin:0px;border: 1px solid; border-color:#ddd;max-width:none;overflow:visible;');
function resizeFrameWidth(){
var frame = document.getElementById('PennyPledge54DT');
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
width = w.innerWidth || e.clientWidth || g.clientWidth;
var margin = 20;
var display_width = width - 40;
if(!mobile){
display_width = 450;
margin = (width-450) / 2;
}
frame.style.width = display_width+"px";
frame.style.left = margin+"px";
}
if(window.attachEvent) {
window.attachEvent('onresize', resizeFrameWidth);
}
else if(window.addEventListener) {
window.addEventListener('resize', resizeFrameWidth, true);
它在我调整窗口大小时有效,但在我缩放时无效。
编辑: 这是请求的 jsfiddle。但是,当您放大内容时,问题就会显现出来。我只知道如何通过移动设备做到这一点。所以我不知道 fiddle 会有多大用处。
https://jsfiddle.net/41y62su7/
编辑 这是我的 iframe 在移动设备上稍微放大页面时的样子的屏幕截图。
最佳答案
这里有一个更简单的方法,无需获取 window.onresize 事件(它在整个 resize 事件中重复触发,而不仅仅是在结束时)即可实现相同的效果。使用下面定义的 heredoc 函数可以提高代码的可维护性和可读性。在此示例中,我包含了您的 javascript 代码中未包含的叠加层。
此方法使用边距使 iframe 在覆盖层中居中,覆盖层固定在一个位置并设置为视口(viewport)的宽度和高度。
function heredoc(f) {
return f.toString().match(/\/\*\s*([\s\S]*?)\s*\*\//m)[1];
};
var overlay = document.createElement("div");
var iframe = document.createElement("iframe");
iframe.setAttribute("src", "https://www.google.ca");
overlay.style.cssText = heredoc(function() {/*
z-index: 2147483647;
position: fixed;
top: 0;
width: 100vw;
height: 100vw;
background: rgba(0,0,0,0.8);
*/});
iframe.style.cssText = heredoc(function() {/*
display: block;
margin-top:20px;
width: 450px;
max-width: 100vw;
height: 150px;
border: 1px solid #ddd;
overflow:visible;
margin: 0 auto;
margin-top: 20px;
*/});
overlay.appendChild(iframe);
document.getElementById('main').appendChild(overlay);
// you can also use
// document.body.appendChild(overlay);
// if you don't want to require that the user have an element with the id main
/* for example only, not required */
body {
width: 1000px;
height: 1000px;
}
<body>
<p id="main">
This is a bunch of text. Yadda yadda.
</p>
</body>
关于Javascript如何在用户放大时将叠加层居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29979608/