我有几个嵌套的可调整大小的 div,需要调整大小以适应子大小。 一切正常,直到我尝试调整其中一个外部 div 的大小(垂直)然后它卡住了。
这是一个 fiddle .
$(function () {
$('.block').resizable();
$('.block').resize(resize_handler);
});
function checkChildren(object) {
$(object).children(".block").each(function (index, item) {
var itemH = $(item).position().top + $(item).height();
var itemW = $(item).position().left + $(item).width();
if ($(object).width() < itemW) {
$(item).width($(object).width());
checkChildren($(item));
}
if ($(object).height() < itemH) {
$(item).height($(object).height());
checkChildren($(item));
}
});
}
function checkParent(e) {
var object = $(e);
var par = object.parent();
var totalW = object.width() + object.position().left;
var totalH = object.height() + object.position().top;
if (totalH > par.height()) {
par.height(totalH);
checkParent(par);
}
if (totalW > par.width()) {
par.width(totalW);
checkParent(par);
}
}
function resize_handler(e, ui) {
e.stopPropagation();
var object = $(this);
var par = object.parent();
if (par.hasClass("block")) {
checkParent(object);
}
if (object.children('.block').length > 0) {
checkChildren(object);
}
}
最佳答案
当然,您已经想到了这一点,但如果父 div 的高度与其子元素的高度太接近,您是否可以尝试限制父 div 的可调整大小。意思是当它即将接触到 child 的边缘时,不要让它靠近。也许在几个像素的 child 周围维护一个缓冲区,这将迫使用户先调整 child ,然后才能将 parent 调整得更小。
只是一个想法。
关于javascript - Jquery resizable auto resize 父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16705373/