我有以下脚本,我需要检测:
- 内容元素有变化(例如大小/位置)或
- body 元素有变化(例如大小/位置)
我无法在按钮本身上执行此逻辑。
有哪些事件可用? 能否请您提供一个代码示例?
http://jsbin.com/sewerumive/1/
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<script>
window.App = {
start: function () {
var btn = document.getElementById('addContent');
btn.addEventListener('click', function () {
var body = document.getElementsByTagName('body')[0];
body.innerHTML += '<p>ADDED LATER - Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industrys standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>';
});
//---
// does not work i need the content
window.addEventListener('resize', function () {
console.log('content / window / resize');
});
var content = document.getElementById('content');
content.addEventListener('change', function () {
console.log('content / div / resize');
}.bind(this));
}
};
</script>
</head>
<body onload="App.start();">
<div id="content">
<button id="addContent" type="button">Add content!</button>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
</div>
</body>
</html>
最佳答案
MutationObserver 提供了一种对 DOM 中的任何更改使用react的方法。
还有这个线程 enter link description here
关于javascript - 如何检测 div 或 body 的变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27836363/