这是如何完成的示例
HTML
<button id="button">Click me</button>
<span id="watch">0.0</span>
JavaScript
/*jslint sub: true, maxerr: 50, indent: 4, browser: true */
/*global */
(function () {
"use strict";
if (typeof window.MutationObserver !== "function") {
window.MutationObserver = window.WebKitMutationObserver || window.MozMutationObserver;
}
var button = document.getElementById("button");
var watch = document.getElementById("watch");
var i = 87;
var stop = 95;
var detect = 91.5;
var step = 0.5;
var id;
function click(obj) {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
return obj.dispatchEvent(evt);
}
function whenClicked() {
alert("I've been clicked!");
}
button.addEventListener("click", whenClicked, false);
if (typeof window.MutationObserver !== "function") {
watch.addEventListener("DOMNodeInserted", function () {
if (parseFloat(watch.textContent) === detect) {
click(button);
}
}, false);
} else {
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
if (mutation.type === 'childList' && mutation.target.id === "watch" && parseFloat(mutation.target.textContent) === detect) {
click(button);
}
});
});
observer.observe(document, {
childList: true,
characterData: true,
subtree: true
});
}
id = setInterval(function () {
i += step;
if (i > stop) {
clearInterval(id);
if (typeof window.MutationObserver !== "function") {
watch.removeEventListener("DOMNodeInserted");
} else {
observer.disconnect();
}
return;
}
watch.textContent = i;
}, 1000);
}());
在jsfiddle 上
当然,您不需要以编程方式单击按钮,只需在达到您想要的条件时执行按钮的功能。