开发小技巧:jQuery处理自适应内容高度的iframe

本文介绍了一种使Iframe能够根据其内部内容自动调整高度的方法,以避免不必要的滚动条出现。该方法通过JavaScript/jQuery来实现,适用于多种浏览器。

前端开发中,我们往往需要处理iframe,可能有的时候希望iframe根据内容自适应高度以便不出现令人烦心的滚动条,下面这段代码可以帮助你实现类似功能。


$(document).ready(function()
        {
                // Set specific variable to represent all iframe tags.
                var iFrames = document.getElementsByTagName('iframe');

                // Resize heights.
                function iResize()
                {
                        // Iterate through all iframes in the page.
                        for (var i = 0, j = iFrames.length; i < j; i++)
                        {
                                // Set inline style to equal the body height of the iframed content.
                                iFrames[i].style.height = iFrames[i].contentWindow.document.body.offsetHeight + 'px';
                        }
                }

                // Check if browser is Safari or Opera.
                if ($.browser.safari || $.browser.opera)
                {
                        // Start timer when loaded.
                        $('iframe').load(function()
                                {
                                        setTimeout(iResize, 0);
                                }
                        );

                        // Safari and Opera need a kick-start.
                        for (var i = 0, j = iFrames.length; i < j; i++)
                        {
                                var iSource = iFrames[i].src;
                                iFrames[i].src="";
                                iFrames[i].src = iSource;
                        }
                }
                else
                {
                        // For other good browsers.
                        $('iframe').load(function()
                                {
                                        // Set inline style to equal the body height of the iframed content.
                                        this.style.height = this.contentWindow.document.body.offsetHeight + 'px';
                                }
                        );
                }
        }
); 

文章来源:http://bbs.html5cn.org/forum.php?mod=viewthread&tid=11622&extra=
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值