iframe在ios宽度扩大解决方案
2018-01-05 本文已影响0人
皮蛋馅儿
样式
<style>
#iframe {
margin-top: 44px;
width: 100%;
height: 100%;
display: block;
vertical-align: bottom;
}
.scroll-wrapper {
-webkit-overflow-scrolling: touch;
overflow: auto;
position: fixed;
right: 0;
left: 0;
top: 0;
bottom: 0;
width: 100%;
height: 100%;
}
</style>
html
<div class="scroll-wrapper">
<iframe frameborder="0" src="https://www.b.com/" id="iframe"
scrolling="true" marginwidth="0" marginheight="0" align="center"></iframe>
</div>
非跨域
$("#iframe")[0].onload = function () {
iosIframeWidthBug();
};
function iosIframeWidthBug() {
if (!navigator.userAgent.match(/iPad|iPhone/i)) {
return false;
}
var iframebody = document.getElementById('iframe').contentWindow.document.body;
iframebody.style.width = document.body.clientWidth + 'px';
}
不跨域以上方法可以完美解决,但是在跨域的情况下,就会报:game:105 Uncaught DOMException: Blocked a frame with origin "http://xxx" from accessing a cross-origin frame.以下是跨域的解决方法:
跨域
a网站主页
<script>
window.onload = function () {
var clientWidth = document.body.clientWidth + 'px';
window.frames[0].postMessage(clientWidth, 'https://www.b.com/');
};
</script>
b网站子页
<script>
window.addEventListener('message', function (e) {
if (e.source != window.parent) return;
var clientWidth = e.data;
$('body').width(clientWidth);
localStorage.setItem('clientWidth', clientWidth);
}, false);
var clientWidth = localStorage.getItem("clientWidth");
if (clientWidth) {
$('body').width(clientWidth);
}
</script>
加我微信公众号【皮蛋馅儿】,一起学习哦~