如何检测DIV的尺寸变化
可以用2种方法来检测div尺寸的变化。
方法1:使用ResizeObserver接口检查变化
ResizeObserver接口用于报告一个元素的尺寸变化。
首先使用jQuery选择要跟踪的元素。一个ResizeObserver对象被创建,它有一个回调函数,定义了当检测到尺寸变化时应该执行的行动。
此对象的observe()方法用于被追踪的元素。这将检查任何变化,并在检测到任何尺寸变化时执行回调函数。
语法:
let resizeObserver = new ResizeObserver(() => {
console.log("The element was resized");
});
resizeObserver.observe(elem);
示例:
<!DOCTYPE html>
<html>
<head>
<title>
How to detect DIV’s dimension changed?
</title>
<style>
#box {
resize: both;
border: solid;
background-color: green;
height: 100px;
width: 100px;
overflow: auto;
}
</style>
</head>
<body>
<h1 style="color: green">
GeeksForGeeks
</h1>
<b>
How to detect DIV’s dimension changed?
</b>
<p>Check the console to know if the div's dimensions have changed.
</p>
<div id="box"></div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js">
</script>
<script>
elem = $("#box")[0];
let resizeObserver = new ResizeObserver(() => {
console.log("The element was resized");
});
resizeObserver.observe(elem);
</script>
</body>
</html>
输出:
- 在调整元素的大小之前。
- 调整元素的大小后。
方法2:每500毫秒检查一次尺寸的变化
这种方法涉及到每隔500毫秒检查要跟踪的元素的尺寸。尺寸的值与上一次迭代的值进行比较,以检查是否有任何差异。
要追踪的元素的高度和宽度是通过jQuery的height()和width()方法找到的。这些尺寸将被用作该元素的最后跟踪的基线尺寸,并存储在一个变量中。
一个新的函数被创建,其中元素的高度和宽度被发现。这将是新的尺寸,将与先前的尺寸进行比较。使用一个if语句,将新的高度和宽度与之前发现的基线进行比较。如果尺寸不匹配,意味着尺寸已经改变。当尺寸改变时,需要采取的行动将在这里执行。
发现的新尺寸将被分配给旧尺寸作为基线,以便下一次迭代可以用它们来检查。
使用setInterval()函数,创建的函数每500毫秒连续循环一次。这将持续检查高度和宽度的变化,并在出现差异时执行给定的函数。
这种方法比前一种方法要慢得多,减少每次检查之间的时间将进一步降低性能。
语法:
let lastHeight = ("#box").height();
let lastWidth =("#box").width();
function checkHeightChange() {
newHeight = ("#box").height();
newWidth =("#box").width();
if (lastHeight != newHeight || lastWidth != newWidth) {
console.log("The element was resized");
// assign the new dimensions
lastHeight = newHeight;
lastWidth = newWidth;
}
}
setInterval(checkHeightChange, 500);
示例:
<!DOCTYPE html>
<html>
<head>
<title>
How to detect DIV’s dimension changed?
</title>
<style>
#box {
resize: both;
border: solid;
background-color: green;
height: 100px;
width: 100px;
overflow: auto;
}
</style>
</head>
<body>
<h1 style="color: green">
GeeksForGeeks
</h1>
<b>
How to detect DIV’s dimension changed?
</b>
<p>Check the console to know if the div's dimensions have changed.
</p>
<div id="box"></div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js">
</script>
<script type="text/javascript">
let lastHeight = ("#box").height();
let lastWidth =("#box").width();
function checkHeightChange() {
newHeight = ("#box").height();
newWidth =("#box").width();
if (lastHeight != newHeight ||
lastWidth != newWidth) {
console.log("The element was resized");
// assign the new dimensions
lastHeight = newHeight;
lastWidth = newWidth;
}
}
setInterval(checkHeightChange, 500);
</script>
</body>
</html>
输出:
- 在调整元素的大小之前。
- 调整元素的大小后。