简体   繁体   English

如何检测元素位置的变化?

[英]How to detect the position of an element changed?

Consider the situation where div-A has a relative position to div-B (actually, div-A is hovering over div-B by different Z-Index ). 考虑以下情况: div-Adiv-B有相对位置(实际上, div-A悬停在div-B上不同的Z-Index )。 When the position of div-B changes, div-C is to be inserted before it and div-A is to be hidden. div-B的位置更改时,将在div-C之前插入div-C ,并隐藏div-A

The question is: how to detect the position changing of div-B ? 问题是:如何检测div-B的位置变化?

That all depends on can cause the divs to move, if it's a window resizing window.onresize = function(){} or in jQuery $(window).resize(function(){}); 如果这是一个调整窗口大小的窗口,那么这一切都可能导致div移动window.onresize = function(){}或在jQuery $(window).resize(function(){});
if it's caused by user interaction (like clicks and what have you): document.body.addEventListener('click',function(){},false); 如果是由用户互动(例如点击和您所拥有的东西)引起的: document.body.addEventListener('click',function(){},false); , where the handler is preferably a closure of sorts, that holds the initial position of the divs in question. ,其中处理程序最好是某种类型的闭包,它保留了相关div的初始位置。
If it's caused by new content inserted due to an ajax call: let the onreadystatechange handler sort it out. 如果是由于ajax调用而插入新内容引起的:让onreadystatechange处理程序对其进行整理。 Again, preferably use a closure to compare the position to the initial values 同样,最好使用闭包将位置与初始值进行比较

There might be an easier CSS3 way, I'm no designer - so I don't really know. 我可能不是CSS设计师,这也许是一种更简单的CSS3方式-所以我真的不知道。 Also: set up a fiddle of what you've tried so far an what your page looks like. 另外:设置到目前为止您尝试过的内容以及页面的外观。 And be a bit more precise about this issue. 并且对此问题要更精确一些。 Your question is terribly vague. 您的问题非常模糊。 Read the FAQ's 阅读常见问题解答

You can use the $.position method in jquery: 您可以在jquery中使用$ .position方法:

  $('#element_id').position().left;
  $('#element_id').position().top;

Just store those in a variable and then actively monitor if it changes using the setInterval() method 只需将它们存储在变量中,然后使用setInterval()方法主动监视其是否发生更改

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM