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

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

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

主要思路是这样的:

每次获取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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: