这个问题在这里已有答案:
我创建了一个模块,用于创建和初始化元素并将其返回给应用程序。然后,应用程序将其附加到DOM。
我想注册(在初始化期间)当元素的宽度发生变化时触发的事件。我知道你可以使用window.resize
在窗口调整大小时接收一个事件,也可能是元素的宽度,但是当它被添加到DOM时(添加它之前是0),宽度也会改变。任何人?
这是您可以检查元素调整大小事件
参考:https://stackoverflow.com/a/39312522/4286794
function outputsize() {
width.value = textbox.offsetWidth
height.value = textbox.offsetHeight
}
outputsize()
new ResizeObserver(outputsize).observe(textbox)
Width: <output id="width">0</output><br>
Height: <output id="height">0</output><br>
<textarea id="textbox">Resize me</textarea><br>
您可以使用jquery的“width”函数来获取元素的宽度。
<script>
$("button").click(function(){
alert("Width of div: " + $("div").width());
});
</script>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
$("button").click(function(){
alert("Width of div: " + $("div").width());
});
});
</script>
<div style="height:100px;width:300px;padding:10px;margin:3px;border:1px solid blue;background-color:lightblue;"></div><br>
<button>Display the width of div</button>
</body>
</html>