javascript JS / jQuery 如何获取动态(响应式)div 的高度?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24191406/
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-10-28 02:20:06  来源:igfitidea点击:

JS / jQuery How to get height of dynamic (responsive) div?

javascriptjqueryhtmlcss

提问by John_911

I have not been able to find an answer that works for me on SO.

我无法在 SO 上找到适合我的答案。

Basically I have a div with an image that has fixed positioning. It is responsive and will shrink or grow to whatever the screen size is.

基本上我有一个带有固定定位图像的div。它是响应式的,可以缩小或增长到任何屏幕尺寸。

What I want to do is get the height anytime the screen size changes and input it as a positioning value for another div so that it there is no overlapping (due to the fixed positioning).

我想要做的是在屏幕尺寸发生变化时获取高度并将其输入为另一个 div 的定位值,以便它没有重叠(由于固定定位)。

I can get the height initially but it never changes after the first value when the screen is being resized.

我最初可以获得高度,但在调整屏幕大小时它永远不会在第一个值之后改变。

quick demo up here: link

快速演示在这里:链接

look in console to see height being returned. notice that it doesn't change when browser is resized.

在控制台中查看返回的高度。请注意,调整浏览器大小时它不会改变。

JS

JS

$(function(){

    var explore = $('#explore').height();
    console.log(explore);

    $( window ).on("resize", function() {
    console.log(explore);
    });

});

I've also tried .css("height")but that didn't fix the issue.

我也试过,.css("height")但这并没有解决问题。

*note the div does not have fixed positioning on this example since it would make the layout more confusing

*注意这个例子中的 div 没有固定的位置,因为它会使布局更加混乱

回答by Simcha Khabinsky

You are not modifying explore:

您没有修改探索:

Change it as follows:

更改如下:

$(function(){

    var explore = $('#explore').css("height");
    console.log(explore);

    $( window ).on("resize", function() {
       explore = $('#explore').css("height");
       console.log(explore);
    });

});

回答by peregrine

You need to add a resize listener to the window like so:

您需要向窗口添加一个调整大小的侦听器,如下所示:

function repositionDivOnResize() {
 // this is where you'll dynamically reposition your element
}

$(window).on("resize", repositionDivOnResize)