作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在修改两个下拉列表的外观。这里没有问题。一切都很好。唯一的问题是 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)
最佳答案
您没有列出目标页面,但它可能使用 AJAX 来设置和/或更改该全局变量。
此外,如果脚本丢失了它的 @grant none
,问题代码将会中断。状态,或者如果您尝试在 Firefox 以外的任何浏览器上使用它。 (除非脚本使用注入(inject)——我们无法从问题中分辨出来。)
要解决 AJAX 问题,请轮询 setInterval()
中的变量。
要使代码更健壮,请使用 unsafeWindow
或 Script Injection。参见 "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;
}
}
}
关于javascript - addEventListener 仅在页面刷新时起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13771066/
我是一名优秀的程序员,十分优秀!