addEventListener只在页面刷新时工作?

时间:2012-12-07 21:13:59

标签: javascript firefox greasemonkey 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 个答案:

答案 0 :(得分:1)

您没有列出目标网页,但它可能使用AJAX来设置和/或更改该全局变量。

此外,如果脚本失去@grant none状态,或者您尝试在除Firefox之外的任何浏览器上使用它,问题代码将会中断。 (除非脚本使用 Injection - 我们无法从问题中分辨出来。)

要解决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;
        }
    }
}