2012-12-07 62 views
2

我正在修改兩個下拉列表的外觀。這裏沒有問題。一切都很好。唯一的問題是addEventListener方法僅適用於頁面刷新。addEventListener只在頁面刷新工作?

如何讓此代碼在頁面加載時工作,而無需點擊刷新按鈕?

window.addEventListener('load', function() 
{ 
    var CityCount = this.character.citynum ; 
    var PosX = parseInt(CityCount) * (-15); 
    var MyHeight = parseInt(CityCount) * 15 - 15; 
    var MyStyle='div#citylist {width: 150px !important; margin-top: ' + PosX + 'px !important; position: absolute !important; height: ' + MyHeight + 'px !important; overflow: auto !important; padding-left: 1px !important}'; 
    addGlobalStyle(MyStyle); 
    addGlobalStyle('div#my_city_list {width: 150px !important; margin-top: 50px !important;}'); 
}, false) 

回答

1

你沒有列表中的目標頁面,但它可能使用AJAX來設置和/或改變全局變量。

此外,如果腳本失去其@grant none狀態,或者您嘗試在除Firefox之外的任何瀏覽器上使用它,問題代碼將會中斷。 (除非腳本使用注入 - 這是我們無法從問題中看出的。)

要解決AJAX問題,請在setInterval()內輪詢變量。
要使代碼更健壯,請使用unsafeWindow腳本注入。有關更多信息,請參見"Accessing Variables from Greasemonkey..."

把它放在一起,這應該工作。不需要addEventListener()

var globScope  = unsafeWindow || window; 
var cityCountTimer = setInterval (styleTheCityList, 333); 

function styleTheCityList() { 
    this.lastCityCount = this.lastCityCount || 0; // Static var for this func 

    if (
      typeof globScope.character   != "undefined" 
     && typeof globScope.character.citynum != "undefined" 
    ) { 
     var CityCount = parseInt (globScope.character.citynum, 10); 
     if (CityCount != this.lastCityCount) { 
      var PosX  = CityCount * (-15); 
      var MyHeight = CityCount * 15 - 15; 
      var MyStyle  = 'div#citylist {width: 150px !important; margin-top: ' 
          + PosX 
          + 'px !important; position: absolute !important; height: ' 
          + MyHeight 
          + 'px !important; overflow: auto !important; padding-left: 1px !important}' 
          ; 
      addGlobalStyle (MyStyle); 
      addGlobalStyle ('div#my_city_list {width: 150px !important; margin-top: 50px !important;}'); 

      this.lastCityCount = CityCount; 
     } 
    } 
} 
+0

非常感謝!你的代碼效果很好。我只需要運行代碼一次,所以我刪除了this.clastCityCount行,並且我添加了_clearInterval(cityCountTimer)_。 – Dani

+0

非常好!真高興你做到了。 –