您的位置:首页 > Web前端 > JQuery

基于JQuery的Iframe自适应

2017-12-26 17:35 183 查看
HTML代码
<html>
<head>
<title>测试页</title>
<meta name="autoHeight" content="default"/>
<!-- 这句meta要加-->
</head>
<body>
</body>
</html>


/**
* iframe自适应代码,可以定义在公共js里
*/
(function () {
if ($("meta[name=autoHeight]").get(0) != undefined) {
var html = "";
html += ' function updateIframe(targetId,height){';
html += ' /*动态拼接的代码*/ \n';
html += ' var stop = false;\n';
html += ' $("iframe").each(function(index,data){\n';
html += ' if(stop){\n';
html += ' return ;\n';
html += ' }\n';
html += ' var src = $(data).attr("src");\n';
html += ' if(src == targetId){\n';
html += ' $(data).height(height);\n';
html += ' stop = true;\n';
html += ' return ;\n';
html += ' }\n';
html += ' });\n';
html += ' }\n';
if (isScroll().scrollY) {
while (isScroll().scrollY) {
var id = window.location.pathname + window.location.search;
var oldHeight = $("body").height();
var newHeight = oldHeight + 100;
$("body").height(newHeight);
if (typeof(parent.updateIframe) === "undefined") {
parent.eval(html);
}
parent.updateIframe(id, newHeight);
}
}
}
})();


/**
* 是否出现滚动条
*/
var isScroll = function (el) {
var elems = el ? [el] : [document.documentElement, document.body];
var scrollX = false,
scrollY = false;
for (var i = 0; i < elems.length; i++) {
var o = elems[i];
// test horizontal
var sl = o.scrollLeft;
o.scrollLeft += (sl > 0) ? -1 : 1;
o.scrollLeft !== sl && (scrollX = scrollX || true);
o.scrollLeft = sl;
// test vertical
var st = o.scrollTop;
o.scrollTop += (st > 0) ? -1 : 1;
o.scrollTop !== st && (scrollY = scrollY || true);
o.scrollTop = st;
}
// ret
return {
scrollX: scrollX,
scrollY: scrollY
};
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息