Javascript中 非Window的DOM的onresize事件解决方案

来源:互联网 发布:镜像变换 矩阵理论 编辑:程序博客网 时间:2024/05/23 00:37

Javascript 中onresize事件我们会在窗口大小发生改变的时候需要自适应的时候应用上,但是如果是这样的场景呢,那就需要想想其他的解决办法了:

场景1:先上图

页面是上下布局的,通过【上箭头】和【下箭头】控制下部div的大小,需求是:下面的图表需要实现根据DIV来实现图表重绘!  


在这种情况下,仅仅有window.onresize的话是不够的,我们需要对监听此DIV的resize从而达到图表的重新绘制功能,贴代码吧:

////this is a Jquery plugin function that fire an event when the size of an element changed //usage $().sizeChanged(function(){})(function ($) {$.fn.sizeChanged = function (handleFunction) {    var element = this;    var lastWidth = element.width();    var lastHeight = element.height();    setInterval(function () {        if (lastWidth === element.width()&&lastHeight === element.height())            return;        if (typeof (handleFunction) == 'function') {            handleFunction({ width: lastWidth, height: lastHeight },                           { width: element.width(), height: element.height() });            lastWidth = element.width();            lastHeight = element.height();        }    }, 100);    return element;};}(jQuery));
有了这段代码的话,我们需要在你需要的地方将对应的DOM绑定上对应的事件处理函数,参考例子:

$(that.dom).sizeChanged(that.myChart.resize);

如果仅仅只想解决你的问题,那倒这里就可以止步了。

**************************************华丽的分割线**************************************

一、相关资料和链接

链接1:http://stackoverflow.com/questions/10086693/jquery-resize-on-div-element

这个我建议好好看一下,很多种相关解决办法,上面的脚本其实也来自于这里;

链接2: http://stackoverflow.com/questions/8053583/jquery-resize-listener-on-a-div


二、实现原理(个人体会,如若不对请往死头喷)

1. 记录div 原来的height和width;

2. 使用setTimeout延时查看div的height和width与以前是不是有变化,如果有变化的话调用绑定的函数;

3. 重复第2步骤

0 0