2012-12-07 63 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

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