如何知道DOM元素何时移动或调整大小 [英] How to know when an DOM element moves or is resized

查看:128
本文介绍了如何知道DOM元素何时移动或调整大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一个要监听的DOM事件告诉我DOM元素移动的时间是重新定位还是在页面上调整大小。我不是在谈论被拖放的元素。一个例子是如果一个页面上有三个项目的列表,我使用JS从页面中删除前两个列表项之一(或隐藏它或其他),我想附加一个处理程序来运行时第三个列表项在页面中向上移动。

I'd like to know if there is a DOM event to listen for that tells me when a DOM element moves is repositioned or is resized on the page. I am not talking about an elements being drag/dropped. An example is if a have a list of three items on a page, and I use JS to remove one of the top two list items from the page (or hide it or whatever), I'd like to attach a handler to run when the third list item gets moved up in the page.

我正在使用jQuery,因此可以接受简单的javascript或jQuery答案。

I am using jQuery, so plain javascript or jQuery answers are acceptable.

也许在元素级别没有移动/位置/调整大小事件,所以如果有一个页面/ doc级别事件会告诉我页面被重新绘制,我可以检查是否需要调用一个函数再次?

Maybe there are no move/position/resize events at the element level, so if there is a page/doc level event that will tell me that the page was repainted and I can check if I need to call a function again?

背景

我在元素上放置一个透明div webservice调用是为了删除该元素。由于我需要绝对定位覆盖div,我希望它能够跟踪它最初覆盖的元素。实际上将它锚定到基本元素。

I put a transparent div over an element while a webservice call is made to delete that element. Since I need to absolutely position that overlay div, I want it to track the element that it covers initially. In effect anchoring it to the base element.

推荐答案

一般来说,你无法获得元素移动/调整大小的回调;你必须不断检查间隔轮询器中的尺寸,这会使响应性降低一些。您可以通过在窗口 resize 上调用检查器来改善这一点(如果涉及溢出或固定定位,则滚动你还可以添加DOM Mutation事件监听器,以便在从文档树中删除元素时获得通知,但这并不适用于所有浏览器。

You can't get a callback for element movement/resizing in general; you would have to keep constantly checking the dimensions in an interval poller, which would make it a bit less responsive. You could improve this by calling the checker on a window resize event too (and scroll if overflow or fixed positioning is involved. You could also add DOM Mutation Event listeners to get informed when elements are removed from the document tree, but this doesn't work in all browsers.

你能不能使用纯CSS进行叠加?例如,在要隐藏的元素上放置 position:relative ,然后在其中添加叠加,使用以下内容?

Can't you do an overlay with plain CSS? eg. put position: relative on the element to be obscured, then add the overlay inside it, with the following?

position: absolute;
z-index: 10;
left: 0;
top: 0;
width: 100%;
height: 100%;
opacity: 0.5;

这篇关于如何知道DOM元素何时移动或调整大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆