起因
今天写页面的时候突然有这么个需求,由于父元素(一个DIV)的height是由javascript计算出来的固定的值,而在其中增加了一个多说插件,在用户评论后,子元素(DIV)的height属性增加,导致子元素溢出。但是又不知道如何为多说的评论按钮增加回调函数,于是乎就想到了根据子元素的大小变化来重新计算父元素的height。
onresize?
平常,都是在整个浏览器窗口变化时触发一个修改布局的回调函数。使用的是window对象的resize事件,利用:
window.onresize = callback;
来绑定。但根据resize事件的target是defaultView (window),这里详见MDN的resize文档,也就是说只有window对象有resize事件,于是乎就想到使用jQuery自己的事件机制来模拟一个普通元素上的resize事件
使用JQUERY事件的实现思路
可以想到一种比较简单的方式:
1. 在元素绑定resize对象时,记录元素的width和height
2. 使用requestAnimationFrame、setTimeout、setInterval,每隔一段时间查询其width和height,如果和记录的width和height不一样,运行回调函数并更新记录中的width为height
JQUERY插件
这个功能Ben Alman编写了一个jQuery插件,传送门
该插件的代码(核心部分),详细代码请查看Ben Alman博客的内容:
(function($, window, undefined) {
var elems = $([]),
jq_resize = $.resize = $.extend($.resize, {}),
timeout_id,
str_setTimeout = 'setTimeout',
str_resize = 'resize',
str_data = str_resize + '-special-event',
str_delay = 'delay',
str_throttle = 'throttleWindow';
jq_resize[str_delay] = 250;
jq_resize[str_throttle] = true;
$.event.special[str_resize] = {
setup: function() {
if (!jq_resize[str_throttle] && this[str_setTimeout]) {
return false;
}
var elem = $(this);
elems = elems.add(elem);
$.data(this, str_data, {
w: elem.width(),
h: elem.height()
});
if (elems.length === 1) {
loopy();
}
},
teardown: function() {
if (!jq_resize[str_throttle] && this[str_setTimeout]) {
return false;
}
var elem = $(this);
elems = elems.not(elem);
elem.removeData(str_data);
if (!elems.length) {
clearTimeout(timeout_id);
}
},
add: function(handleObj) {
if (!jq_resize[str_throttle] && this[str_setTimeout]) {
return false;
}
var old_handler;
function new_handler(e, w, h) {
var elem = $(this),
data = $.data(this, str_data);
data.w = w !== undefined ? w : elem.width();
data.h = h !== undefined ? h : elem.height();










