问题
I´m modifying the appearance of two drop down lists. No problems here. Everything works great. The only issue is that the addEventListener method only works at page refresh.
How do I make this code work at page load without hitting the refresh button?
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:
You didn't list the target page, but it probably uses AJAX to set and/or change that global variable.
In addition, the question-code will break if the script loses its @grant none status, or if you try to use it on any browser but Firefox. (Unless the script uses Injection -- which we can't tell from the question.)
To get around the AJAX problem, poll for the variable inside a setInterval().
To make the code more robust, use unsafeWindow or Script Injection. See "Accessing Variables from Greasemonkey..." for more information.
Putting it all together, this should work. addEventListener() is not needed:
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;
}
}
}
来源:https://stackoverflow.com/questions/13771066/addeventlistener-only-working-at-page-refresh