在其他大网站上看到了html源码在线预览的功能,自己心痒也做了一个,其中使用了iframe标签。在此分享有关它的一些问题:写入html代码,高度自适应,加载onload方法。
iframe 写入html代码
这是项目中使用到的,idName是id的值,错误的写法是直接用html("iframe...");导致的结果就是没内容
var ifmWin=$("<iframe id='htmlView' scrolling='no' frameborder='0'></iframe>").appendTo("pre").get(0).contentWindow;
ifmWin.document.write($(idName).text());
$(idName).html("");
$(idName).append(ifmWin);
高度自适应
网上有很多方法,但是让我最满意的是这个:http://www.cnblogs.com/slyzly/articles/2422737.html
var browserVersion = window.navigator.userAgent.toUpperCase();
var isOpera = browserVersion.indexOf("OPERA") > -1 ? true : false;
var isFireFox = browserVersion.indexOf("FIREFOX") > -1 ? true : false;
var isChrome = browserVersion.indexOf("CHROME") > -1 ? true : false;
var isSafari = browserVersion.indexOf("SAFARI") > -1 ? true : false;
var isIE = (!!window.ActiveXObject || "ActiveXObject" in window);
var isIE9More = (! -[1, ] == false);
function reinitIframe(iframeId, minHeight) {
try {
var iframe = document.getElementById(iframeId);
var bHeight = 0;
if (isChrome == false && isSafari == false)
bHeight = iframe.contentWindow.document.body.scrollHeight;
var dHeight = 0;
if (isFireFox == true)
dHeight = iframe.contentWindow.document.documentElement.offsetHeight + 2;
else if (isIE == false && isOpera == false)
dHeight = iframe.contentWindow.document.documentElement.scrollHeight;
else if (isIE == true && isIE9More) {//ie9+
var heightDeviation = bHeight - eval("window.IE9MoreRealHeight" + iframeId);
if (heightDeviation == 0) {
bHeight += 3;
} else if (heightDeviation != 3) {
eval("window.IE9MoreRealHeight" + iframeId + "=" + bHeight);
bHeight += 3;
}
}
else//ie[6-8]、OPERA
bHeight += 3;
var height = Math.max(bHeight, dHeight);
if (height < minHeight) height = minHeight;
iframe.style.height = height + "px";
} catch (ex) { }
}
function startInit(iframeId, minHeight) {
eval("window.IE9MoreRealHeight" + iframeId + "=0");
window.setInterval("reinitIframe('" + iframeId + "'," + minHeight + ")", 100);
}
加载onload方法
因为iframe中的html代码是浏览器加载结束后填充的,加载onload方法变得有些麻烦,在不断尝试和实践中,如下可以解决window.onload = onloadMethod();
function onloadMethod(){...}
注意js要放在body内。
更多干货等你来拿:http://www.itit123.cn/blog/detail/16.html