jQuery jquery在div上调整监听器的大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8053583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 09:56:24  来源:igfitidea点击:

jquery resize listener on a div

jqueryresizelistener

提问by Peter

This is the situation, I have 2 div's next to each other. One div is very dynamic in height, which basically means it can grow and shrink to accommodate for it's content. For example, this div has content that can be folded open or close, or containers that can expand to fit ajax loaded content.

这就是情况,我有 2 个相邻的 div。一个 div 在高度上是非常动态的,这基本上意味着它可以增长和缩小以适应它的内容。例如,这个 div 具有可以折叠打开或关闭的内容,或者可以扩展以适应 ajax 加载内容的容器。

Now, next to this div is another one that neatly follows the height of the first one through css. Works great. But here is the question: I would like to change the content of this second div depending on its height.

现在,在这个 div 旁边是另一个 div,它通过 css 整齐地跟随第一个 div 的高度。效果很好。但问题是:我想根据其高度更改第二个 div 的内容。

In other words, div 1 changes in size, div 2 follows through css and I now need to trigger an ajax call to re-fill div 2 with new content, befitting it's new size.

换句话说,div 1 的大小发生了变化,div 2 通过 css 跟随,我现在需要触发 ajax 调用以用新内容重新填充 div 2,以适应它的新大小。

Has anybody an idea how I can do this with jquery? If possible, without the use of timeouts?

有没有人知道我如何用 jquery 做到这一点?如果可能,不使用超时?

Cheers.

干杯。

回答by Kato

As the thread poelinca providedsuggests, there are some nice plugins available for this functionality.

正如poelinca 提供的线程所暗示的那样,有一些不错的插件可用于此功能。

If you don't like the plugin idea, another simple solution would be to simply trigger a "resize" event on the div whenever the content is modified. Then you could monitor it with resize() as expected, utilizing an elegant observer pattern.

如果您不喜欢插件的想法,另一个简单的解决方案是在修改内容时简单地在 div 上触发“调整大小”事件。然后,您可以按预期使用 resize() 监视它,利用优雅的观察者模式

function appendContent($div, content) {
   $div.append(content).trigger($.Event('resize'));
}

$div.bind('resize', function(e) {
   // all your magic resize mojo goes here
});

回答by Jaroslav ?treit

https://github.com/sdecima/javascript-detect-element-resize

https://github.com/sdecima/javascript-detect-element-resize

Works like a charm!

奇迹般有效!

I′ve tested attrchange but this was not working, lost 2hours of work :(

我已经测试了 attrchange 但这不起作用,失去了 2 小时的工作时间:(

回答by Naftali aka Neal

The only thing I could think of is having some timer checking the height every Xseconds.

我唯一能想到的是让一些计时器每秒钟检查一次高度X

Something like this:

像这样的东西:

function checkHeightTimer(){
    var div1 = $('#div1');
    var div2 = $('#div2');
    var somesize = #somenumber here;
    if(div1.height() > somesize){
        //do something to div2
    }
    setTimeout(checkHeightTimer, 500); //at 500 miliseconds
}