這是它如何工作的一個示例
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
當然,您不需要以編程方式單擊該按鈕,只需在達到所需條件時執行按鈕的功能即可。
如何生成跨度中的值? – Xotic750 2013-04-27 21:46:52
我不相信這可以工作,點擊按鈕必須是用戶發起的,而不是程序化的。但是,您可以檢查該值,然後以編程方式調用該函數(或任何您想要的清除操作)。 – 2013-04-27 21:46:55
你可以用JavaScript點擊一個按鈕,沒問題。 – Xotic750 2013-04-27 21:47:37