Как обнаружить изменения в div или теле?

У меня есть следующий скрипт, мне нужно обнаружить:

  • элемент содержимого изменился (например, размер / положение) или
  • элемент 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>

3 ответа

Решение

MutationObserver предоставляет способ реагировать на любые изменения в DOM.

Узнайте больше на MDN или MSDN

а также эту тему введите описание ссылки здесь

Еще одно предложение (не уверен, что оно будет соответствовать вашим требованиям), вы можете создать собственное событие и вызвать его, когда захотите:

window.App = {
    start: function () {
        var customEvent = new Event("customEvent"), // your custom event
            content = document.getElementById('content'),
            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>';

            // trigger it
            content.dispatchEvent(customEvent);
        });
        
        content.addEventListener('customEvent', function () {
            console.log('content / div / resize');
        });
    }
};
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>

Проверьте эту ссылку

И вместо "изменения" используйте "DOMNodeInserted" и измените html div с идентификатором содержимого вместо innerHTML тела

Ты можешь видеть content / div / resize в консоли браузера

Другие вопросы по тегам