offsetheight
One of the (perceived) tricky tasks within front-end coding is checking if an element is visible or not. The very naive way of checking if an element is visible (i.e. has presence or takes up space on the page) is by checking its display style value:
前端编码中的(感知到)棘手任务之一是检查元素是否可见。 检查元素是否可见(即页面上是否存在或占用空间)的一种非常幼稚的方法是检查其显示样式值:
var incorrectIsVisible = window.getComputedStyle(someElement, null).getPropertyValue('display'); // "inline", "inline-block", "block", etc.Notice I'm not checking the opacity as well because an invisible element still takes up space on the screen. The problem with the code above is that you can gain the style of a child but that may not matter if its parent is set to display: none. For example, if the child's display style value is inline-block, but the element's parent display style is none, the child element is still not visible. Oddly enough, checking the child element's offsetHeight value will signal if the element is likely visible:
请注意,我也没有检查不透明度,因为不可见的元素仍会占用屏幕空间。 上面的代码的问题在于,您可以获得孩子的样式,但是如果其父对象设置为display: none ,则可能没有关系。 例如,如果子级的display样式值为inline-block ,但元素的父级display样式为none ,则子元素仍然不可见。 奇怪的是,检查子元素的offsetHeight值将表明该元素是否可能可见:
var correctIsVisible = someElement.offsetHeight; // 0 for hidden, more than 0 for displayingIf the element is a child of an element which is display: none, the offsetHeight will be 0 and thus you know the element is not visible despite its display value. Again, remember that opacity is not considered and an element which is opacity: 0 is still technically visible, taking up space.
如果该元素是display: none元素的子元素display: none ,则offsetHeight将为0,因此您知道该元素尽管display值仍不可见。 同样,请记住,不考虑不透明度,并且元素是opacity: 0在技术上仍然可见,占用空间。
翻译自: https://davidwalsh.name/offsetheight-visibility
offsetheight