MutationObserver對象的使用

問題:在對div設置屬性 contenteditable="true" 的時候,由於需要對輸入的內容變化進行監聽,由於在ie中使用 input、change、propertychange等事件進行監聽的時候,無法監聽到輸入內容的變化,所以這裏使用了MutationObserver對象來實現。

使用方式如下:

    //ie下無法監聽輸入變化,使用下面的方法監聽
    // 設置observer的配置選項
    var config = { attributes: true, childList: true, subtree: true,characterData:true };
    // 當節點發生變化時的需要執行的函數
    var callback = (mutationsList, observer) => {
        for(var mutation of mutationsList) {
            if (mutation.type == 'childList') {
                this.changeTxt()
            }
            else if (mutation.type == 'attributes') {
                this.changeTxt()                
            } else if(mutation.type == 'characterData'){
                this.changeTxt()              
            }
        }
    };
    // 創建一個observer示例與回調函數相關聯
    var observer = new MutationObserver(callback);
    //使用配置文件對目標節點進行觀測
    observer.observe(this.$refs.contentEditor, config);

備註:

1、上面代碼裏面`this.$refs.contentEditor`是需要監聽的dom元素,根據實際監聽對象來修改。

2、`this.changeTxt()`是監聽到文本變化執行的相應函數,根據實際需求來修改。

MutationObserver屬性傳送門:點這裏

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章