可编辑iframe高度自适应(编辑器所见即所得模式) ----- JQUERY特效模板

        之前做过高度自适应,但是始终效果不理想,后来看到一个比较好的办法,实现了之后,特保留一份模板,方便以后类似应用。

          主要思路是这样的:

                  每次获取iframe中高度的时候,在iframe的最底端插入一个span,其代码如下:

<span id="height_counter" style="display:block;width:0;margin:0;padding:0;border:0;clear:both;">.</span>
                 然后通过获取此span及其offsetParent的offsetTop进行累加来计算实际内容的高度。

       

                 $(document).ready(
			function()
			{
				$.extend(
					{
						getXY: function (element)                  //累加内容高度
						{
							var x = 0, y = 0;
							while (element.offsetParent) 
							{
								y += element.offsetTop;
								x += element.offsetLeft;
								element = element.offsetParent;
							}
							return {
								'x': x,
								'y': y
							};
						}
					}
				);
			
				$.extend(
					{
						setHeight:function()					//设置iframe高度
						{
							/*if(_G_val.win_scro_top == 0)
							{*/
								_G_val.win_scro_top = $(window).scrollTop();
							//}
							var _obj = $(document.getElementById(_G_val.editor_elem).contentWindow.document);
							if (_obj.find("#height_counter").length <= 0) 
							{
								_obj.find("body").eq(0).append('<span id="height_counter" style="display:block;width:0;margin:0;padding:0;border:0;clear:both;">.</span>');
							}
							var currentHeight = Math.max($.getXY(_obj.find("#height_counter").get(0)).y + _obj.find("#height_counter").get(0).offsetHeight, _G_val.initheight);
							if (currentHeight != _G_val.lastHeight) 
							{
								$("#editor_container").height(currentHeight);
								$(window).scrollTop((currentHeight - _G_val.initheight)+_G_val.win_scro_top + 50);
								_G_val.lastHeight = currentHeight;
							}
							_obj.find("#height_counter").eq(0).remove();
						}
					
					}
				);
				
				$(document.getElementById(_G_val.editor_elem).contentWindow.document).bind('keyup mouseup keydown',
					function()
					{
						$.setHeight();
					}
				);
				
				$(document.getElementById(_G_val.editor_elem).contentWindow.document).find('body').attr('contenteditable',true).css({"background-color": "rgb(240, 236, 233)", "text-align": "left","overflow-y": "hidden"});
				_G_val.initheight = $(document.getElementById(_G_val.editor_elem).contentWindow.document).height();
			}
		);



           因为此处无法上传附件,所以实例部分,只能放到资源中,此处附上资源链接:

http://download.csdn.net/detail/ivyandrich/6996803


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值