【问题标题】:how detect an element move (changing position) in document? [closed]如何检测文档中的元素移动(改变位置)? [关闭]
【发布时间】:2021-07-20 10:37:09
【问题描述】:

我想检测页面中的元素移动。例如,我有一个带有 offsetheight: 200px 和 offsetleft: 200px 的底部,我希望有一个侦听器来检测元素位置是否已更改(未调整大小

【问题讨论】:

  • 欢迎来到stackoverflow!请将您现有的代码添加到问题中,以便社区成员可以调试并提供一个好的解决方案。阅读有关最小可重现示例的更多信息:stackoverflow.com/help/minimal-reproducible-example
  • 元素是如何被移动的? (例如,删除并重新附加,或者只是样式被更改或......)。

标签: javascript html css angular typescript


【解决方案1】:

您可以使用 MutationObserver 检测元素上的属性是否已更改,或者是否已从 DOM 中添加/删除某些内容。

这是一个简单的示例,其中正文中任何位置的更改都由 console.log 记录。然后可以读取您感兴趣的按钮的偏移量,并对照原始按钮检查它是否已移动。

<!doctype html>
<html>
<head>
<title>Observe</title>
<style>
.movedown {
  position: relative;
  width: 30vmin;
  height: 30vmin;
}
.button {
  width: 20vmin;
  height: 20vmin;
  background: pink;
}
</style>
</head>
<body>
<button onclick="this.classList.toggle('movedown');console.log('button.offsetTop = ' + button.offsetTop);">CLICK ME TO EXTEND/SHRINK ME SO THE OTHER BUTTON MOVES</button>
<button class="button">I AM THE BUTTON YOU ARE INTERESTED IN SEEING WHEN I HAVE MOVED</button>
<div></div>
<script>
//This script copied almost complete from MDN
// Select the node that will be observed for mutations
const targetNode = document.body;
const button = document.querySelector('.button');


// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };

// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
    // Use traditional 'for loops' for IE 11
    for(const mutation of mutationsList) {
        if (mutation.type === 'childList') {
            console.log('A child node has been added or removed.');
        }
        else if (mutation.type === 'attributes') {
            console.log('A ' + mutation.attributeName + ' attribute was modified.');
        }
    }
};

// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);
</script>
</body>
</html>

取自 MDN 的代码,可以找到有关观察此类突变的更多信息。

【讨论】:

  • tnx 对于您的评论,这只适用于您的元素属性,如左上角等,但当它移动另一个元素时,它的顶部和左侧和右侧不会改变并且偏移顶部和偏移左侧的变化我想要检测元素的偏移变化
  • 对不起,我误解了元素是如何移动的,我以为是通过一些鼠标操作或其他方式。因此,您需要在 DOM 中查找任何突变,然后检查该特定元素的偏移量是否发生了变化?我会尽快更新我的答案。
  • tnx 为您解答;这对我有用,但这是整个 document.body 中的侦听器,而不是特殊元素;有什么办法可以收听特殊的元素偏移变化
  • 我不这么认为,因为当我们在我的原始答案中仅在一个元素上寻找突变时,它只会感知属性变化或树结构变化。由于任何事情都可能改变偏移量,我认为您必须仔细聆听。
猜你喜欢
  • 2014-10-21
  • 1970-01-01
  • 1970-01-01
  • 2015-03-13
  • 2018-08-20
  • 2015-09-26
  • 1970-01-01
  • 1970-01-01
  • 2010-10-19
相关资源
最近更新 更多