本文介绍了如何获得clientWidth& DIV之前的clientHeight可见的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取DIV元素的尺寸(用于在光标位置显示弹出菜单),而它是 style.display ='none;',但是DIV的尺寸总是返回0.我似乎能够获得尺寸的唯一方法是将DIV style.display ='block;'设为0, 0,然后将其移动到所需的位置,但看起来很跳跃。

I want to obtain the dimensions of a DIV element (used to display a popup menu at the cursor position) while it's style.display='none;', however the dimensions of the DIV always return 0. The only way I seem to be able to get the dimensions is to make the DIV style.display='block;' at 0,0 and then move it to the required position, but that looks jumpy.

我尝试在可见屏幕区域外显示DIV,但这不起作用。有没有办法在隐藏DIV的同时获得 clientWidth clientHeight 值?

I've tried making the DIV visible outside of the visible screen area but that doesn't work. Is there a way to get the clientWidth and clientHeight values whilst the DIV is hidden?

推荐答案

如果您的DIV不可见,您将无法获得其尺寸。

If your DIV is not visible, you won't be able to get its dimensions.

但是,有一种解决方法。你的div必须是可见的,但这并不意味着它的不透明度和位置必须是1和相对的。

However, there is a workaround. Your div has to be "visible", but that doesn't mean it's opacity and position have to be 1 and relative.

将不透明度设置为0并将位置设置为绝对,你将能够获得DIV尺寸。

Set the opacity to 0 and the position to "absolute" and you'll be able to get the DIV dimensions.

编辑

由于我认为会有更多人遇到类似的问题,我觉得我应该多解释一下我的答案。

Since I think more people will have a similar problem, I feel I should explain my answer a little more.

如果你试图获得使用JavaScript的隐藏元素的大小,你总是会得到0.

If you try to get the size of a hidden element with JavaScript, you will always get 0.

因此,有些技术可以在不向用户显示元素的情况下获得实际大小。我最喜欢的是上面已经写过的那个。以下是更详细的步骤:

So there are techniques to get the real size without displaying the element to the user. My favourite is the one I already wrote about above. Here are the more detailed steps:


  1. 您将元素不透明度设置为0.这样它就不会显示给在获得尺寸时最终用户。

  1. you set the elements opacity to 0. This way it won't be displayed to the end user while you are getting the dimensions.

您将元素位置设置为绝对。这样就不会占用任何空间。

you set the element position to "absolute". This way it won't take up any space.

现在将显示设置为inline-block是安全的。

now it's safe to set the display to "inline-block".

您阅读了元素维度。这次你将得到实际值。

you read the elements dimensions. This time you'll get the real values.

你将显示设置回隐藏并将不透明度和位置设置回原始值。 / p>

You set the display back to "hidden" and set the opacity and position back to its original values.

现在你有一个隐藏元素的大小。

And now you have the size of a hidden element.

这篇关于如何获得clientWidth& DIV之前的clientHeight可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 02:48