2012-06-05 50 views
0

我試圖在GreaseMonkey中製作一個玩具腳本,當我點擊一個按鈕時會導致我的屏幕反覆跳到屏幕的頂部,並且當我再次單擊該按鈕時停止跳躍。Greasemonkey腳本似乎忽略了setInterval?

這是我的代碼:

var perpetualScroll = function() { 
    var scrolling = false; 

    var scroll = function() { 
     if (scrolling) { 
      window.scrollTo(0, 0); 
     } 
    }; 

    var scrollDiv = document.createElement("div"); 
    scrollDiv.id = "topScroll0x2a"; 
    scrollDiv.innerHTML = '<a class="topScroll" onclick="scrolling = !scrolling;" style="display:block; position:fixed; bottom: 1em; right: 1em; color:#fff; background-color:#000; padding:.5em;" href="#">Start scroll</a>'; 
    document.body.appendChild(scrollDiv); 

    var intervalId = window.setInterval(scroll, 50); 
}; 

perpetualScroll(); 

當我點擊下角的腳本創建,它跳轉到屏幕的頂部,但不會持續永遠這樣做的按鈕。

我對Javascript和GreaseMonkey非常陌生,所以我不太清楚問題在哪。我懷疑這可能是由於鏈接的onclick部分存在問題,但如果是這樣,我似乎無法弄清楚。

回答

1

這樣做onclick就像你所期望的那樣工作。你的innerHTML只是一個字符串,所以JS不知道它的範圍在perpetualScroll函數中。

onclick處理程序,它串在全球範圍內進行評估,所以你有什麼是相同的:

window.scrolling = !window.scrolling; 

你想要的scrolling變量是不同的。

您應該創建一個實際的功能是這樣的:

var a = document.createElement('a'); 
a.className = (a.className || "") + ' topScroll'; 
a.style.display = 'block'; 
a.style.position = 'fixed'; 
a.style.bottom = '1em'; 
a.style.right = '1em'; 
a.style.color = '#FFF'; 
a.style.backgroundColor = '#000'; 
a.style.padding = '0.5em'; 
a.href = '#'; 
a.onclick = function(e){ 
    scrolling = !scrolling; 
    return false; 
}; 
scrollDiv.appendChild(a); 

顯然設置,CSS是可怕的,所以你應該真正把在一個單獨的樣式表反正。

+0

哦,這看起來好像是一個更好的方法。我不知道你可以做像'a.style.blah'這樣的東西,謝謝! (是的,我會做一個單獨的樣式表,但我感覺很懶:D) – Michael0x2a