3

Let's say I have a span such as this

<span id="theSpan"></span>

Using WebKitMutationObserver (I'm developing an extension for chrome, so no worries about cross-browser issues), how do i listen for changes within the span (innerText)? ie. the event should fire when i do this:
Javascript

$("#theSpan").text('hello world');

HTML

<span id="theSpan">Hello World</span>
4

2 回答 2

6

You'll need to create WebKitMutationObserver instance, and then simply attach it to your <span> using observe method. The code will look like this:

// find element and create an observer instance
var target = $('#theSpan');
var observer = new WebKitMutationObserver(function(mutations) {
    $('#log').text('input text changed: "' + target.text() + '"');
});
observer.observe(target[0], { childList: true});
//observer.disconnect(); - call this to stop observing

// test case
setInterval(function(){
    target.text('hello world ' + Math.random() + '!!!');
},1000);
​

Don't forget to pass real DOM object to observer, not jQuery object. Working fiddle available here

于 2012-11-21T18:43:13.800 回答
1

Try this:

var target = document.querySelector('#in1');
var display = document.querySelector('#dsp');
var MO = MutationObserver || WebKitMutationObserver || MozMutationObserver; 
var observer = new MO(function(mutations) {
  var _this = this;
  mutations.forEach(function(mutation) {
    dsp.innerHTML = _this._root.innerText || _this._root.textContent;
  });    
});

var config = { 	//attributes: true, 
								//childList: true, 
                characterData: true, 
                subtree: true 
                };
 
observer.observe(target, config);
observer._root = target;

setInterval(function(){},250);
div{
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  border-radius: 5px;
  margin: 0 0 0.75rem 0;
  padding: 0.1rem 0.25rem 0.1rem 0.25rem;
  font-family: sans-serif;
  color: gray;
}

.input{
  border: 1px solid lightblue;
  min-height: 1.25rem;
}
.display{
  border: 1px solid gray;
  background-color: white;
  min-height: 5rem;
}
<div id="in1" class="input" contenteditable="true"></div>
<div id="dsp" class="display"></div>

I think the code is a self-explanatory. Maybe one thing to note - the empty SetInterval. This is because of MAC OS Safari in which, I do not know why, MutationObserver do not work as expected w/o SetInterval. You can play with the interval value, lower value means more responsive MO. In other browsers (Chrome and Firefox - on MAC OS) it works well even w/o SetInterval.

于 2016-03-03T21:04:18.683 回答