提问人:Bob Somers 提问时间:10/6/2008 最后编辑:T JBob Somers 更新时间:3/31/2022 访问量:210414
使用 jQuery 检测 div 的高度何时更改
Detecting when a div's height changes using jQuery
问:
我有一个 div,其中包含一些动态添加和删除的内容,因此它的高度经常变化。我还有一个 div,它绝对位于 javascript 的正下方,所以除非我能检测到 div 的高度何时发生变化,否则我无法将 div 重新定位在它下面。
那么,我怎样才能检测该 div 的高度何时发生变化呢?我假设我需要使用一些jQuery事件,但我不确定要挂接到哪一个。
答:
可以使用 DOMSubtreeModified 事件
$(something).bind('DOMSubtreeModified' ...
但是,即使尺寸不改变,这也会触发,并且每当触发时重新分配位置可能会对性能造成影响。根据我使用这种方法的经验,检查尺寸是否发生了变化更便宜,因此您可以考虑将两者结合起来。
或者,如果您直接更改 div(而不是用户输入以不可预测的方式更改 div,例如如果它是 contentEditable),则只需在执行此操作时触发自定义事件即可。
缺点:IE 和 Opera 不实现此事件。
评论
这是我最近处理这个问题的方式:
$('#your-resizing-div').bind('getheight', function() {
$('#your-resizing-div').height();
});
function your_function_to_load_content() {
/*whatever your thing does*/
$('#your-resizing-div').trigger('getheight');
}
我知道我迟到了几年,只是认为我的答案将来可能会对一些人有所帮助,而无需下载任何插件。
评论
响应 user007:
如果元素的高度由于附加到元素中的项目而发生变化,则无需检测高度的变化。只需将第二个元素的重新定位添加到将新内容附加到第一个元素的同一函数中即可。.append()
如:
$('.class1').click(function () {
$('.class1').append("<div class='newClass'><h1>This is some content</h1></div>");
$('.class2').css('top', $('.class1').offset().top + $('.class1').outerHeight());
});
我在某个时候为 attrchange listener 编写了一个插件,它基本上在属性更改时添加了一个侦听器函数。尽管我把它说成一个插件,但实际上它是一个简单的函数,写成一个jQuery插件。所以如果你愿意..剥离插件专用代码,使用核心功能。
注意:此代码不使用轮询
看看这个简单的演示 http://jsfiddle.net/aD49d/
$(function () {
var prevHeight = $('#test').height();
$('#test').attrchange({
callback: function (e) {
var curHeight = $(this).height();
if (prevHeight !== curHeight) {
$('#logger').text('height changed from ' + prevHeight + ' to ' + curHeight);
prevHeight = curHeight;
}
}
}).resizable();
});
插件页面:http://meetselva.github.io/attrchange/
缩小版本: (1.68kb)
(function(e){function t(){var e=document.createElement("p");var t=false;if(e.addEventListener)e.addEventListener("DOMAttrModified",function(){t=true},false);else if(e.attachEvent)e.attachEvent("onDOMAttrModified",function(){t=true});else return false;e.setAttribute("id","target");return t}function n(t,n){if(t){var r=this.data("attr-old-value");if(n.attributeName.indexOf("style")>=0){if(!r["style"])r["style"]={};var i=n.attributeName.split(".");n.attributeName=i[0];n.oldValue=r["style"][i[1]];n.newValue=i[1]+":"+this.prop("style")[e.camelCase(i[1])];r["style"][i[1]]=n.newValue}else{n.oldValue=r[n.attributeName];n.newValue=this.attr(n.attributeName);r[n.attributeName]=n.newValue}this.data("attr-old-value",r)}}var r=window.MutationObserver||window.WebKitMutationObserver;e.fn.attrchange=function(i){var s={trackValues:false,callback:e.noop};if(typeof i==="function"){s.callback=i}else{e.extend(s,i)}if(s.trackValues){e(this).each(function(t,n){var r={};for(var i,t=0,s=n.attributes,o=s.length;t<o;t++){i=s.item(t);r[i.nodeName]=i.value}e(this).data("attr-old-value",r)})}if(r){var o={subtree:false,attributes:true,attributeOldValue:s.trackValues};var u=new r(function(t){t.forEach(function(t){var n=t.target;if(s.trackValues){t.newValue=e(n).attr(t.attributeName)}s.callback.call(n,t)})});return this.each(function(){u.observe(this,o)})}else if(t()){return this.on("DOMAttrModified",function(e){if(e.originalEvent)e=e.originalEvent;e.attributeName=e.attrName;e.oldValue=e.prevValue;s.callback.call(this,e)})}else if("onpropertychange"in document.body){return this.on("propertychange",function(t){t.attributeName=window.event.propertyName;n.call(e(this),s.trackValues,t);s.callback.call(this,t)})}return this}})(jQuery)
评论
使用 css-element-queries 库中的调整大小传感器:
https://github.com/marcj/css-element-queries
new ResizeSensor(jQuery('#myElement'), function() {
console.log('myelement has been resized');
});
它使用基于事件的方法,不会浪费您的 CPU 时间。适用于所有浏览器,包括 IE7+。
评论
可以使用 MutationObserver
类。
MutationObserver
为开发人员提供了一种对 DOM 中的更改做出反应的方法。它被设计为替代 DOM3 事件规范中定义的突变事件。
示例(来源)
// select the target node
var target = document.querySelector('#some-id');
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation.type);
});
});
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };
// pass in the target node, as well as the observer options
observer.observe(target, config);
// later, you can stop observing
observer.disconnect();
评论
您可以创建一个简单的 setInterval。
function someJsClass()
{
var _resizeInterval = null;
var _lastHeight = 0;
var _lastWidth = 0;
this.Initialize = function(){
var _resizeInterval = setInterval(_resizeIntervalTick, 200);
};
this.Stop = function(){
if(_resizeInterval != null)
clearInterval(_resizeInterval);
};
var _resizeIntervalTick = function () {
if ($(yourDiv).width() != _lastWidth || $(yourDiv).height() != _lastHeight) {
_lastWidth = $(contentBox).width();
_lastHeight = $(contentBox).height();
DoWhatYouWantWhenTheSizeChange();
}
};
}
var class = new someJsClass();
class.Initialize();
编辑:
这是一个类的示例。但你可以做一些最简单的事情。
您可以使用它,但它仅支持 Firefox 和 Chrome。
$(element).bind('DOMSubtreeModified', function () {
var $this = this;
var updateHeight = function () {
var Height = $($this).height();
console.log(Height);
};
setTimeout(updateHeight, 2000);
});
非常基本但有效:
function dynamicHeight() {
var height = jQuery('').height();
jQuery('.edito-wrapper').css('height', editoHeight);
}
editoHeightSize();
jQuery(window).resize(function () {
editoHeightSize();
});
评论
如今,还可以使用 Web API ResizeObserver
。
简单示例:
const myElement = document.querySelector('#myElement');
const resizeObserver = new ResizeObserver(() => {
console.log('size of myElement changed');
});
resizeObserver.observe(myElement);
评论