IE7的CSS相对位置与Javascript错误 [英] IE7 css block relative position with Javascript bug
问题描述
我有一个简单的JS脚本,它在给定值时将CSS块移动到特定路径。
I have a simple JS script that moves a CSS block at a specific path when a value is given to it.
您可以在这里查看代码 http://jsfiddle.net/rayshinn/6DGfb/
You can take a look at the code here http://jsfiddle.net/rayshinn/6DGfb/
这段代码似乎在IE7以外的Chrome和Firefox上运行良好。
This code seem to work fine on Chrome and Firefox except IE7.
我从IE获得的错误如下所示:
The error I get from IE is as follows
Line: 27
Char:13
Error: Object doesn't support this property or method
Code: 0
URL: http://localhost/test/js/plot.js
第27行是如下所示:
Line 27 is as follows
marker = document.getElementById("marker");
this.setPosition(INITIAL_X, INITIAL_Y);
以下是我的完整JS脚本供您参考。
Below is my full JS script for your reference.
(function () {
var INITIAL_X = 550,
INITIAL_Y = 152;
// f(v) -> {"x" : x, "y" : y}
var calculatePosition = function (value) {
var result = {};
result.x = INITIAL_X - value / 9;
result.y = INITIAL_Y + 0.117 * value/ 9 ;
return result;
}
var map = {
marker : null,
value : 0,
setPosition : function (x, y) {
marker.style.left = x + "px";
marker.style.top = y + "px";
},
init : function () {
marker = document.getElementById("marker");
this.setPosition(INITIAL_X, INITIAL_Y);
},
increment : function () {
this.value++;
var result = calculatePosition(this.value);
this.setPosition(result.x, result.y);
},
decrement : function() {
this.value--;
var result = calculatePosition(this.value);
this.setPosition(result.x, result.y);
}
};
map.init();
for (var i = 0; i < 100; i++) {
map.increment();
}
})();
感谢您花时间阅读本文并帮助我解决此问题。
与往常一样,任何建议都将不胜感激!
Thank you for taking your time to read this and helping me solve this issue. As always any suggestions will be greatly appreciated!
推荐答案
问题在于
The problem is the line
marker = document.getElementById("marker");
marker
不会解析为属性您的代码似乎期望您的 map
对象;相反,它解析为全局对象的属性。但是,IE会使用其名称与页面内元素ID相对应的属性填充全局对象,然后不允许您覆盖这些元素。这意味着在IE中已经有一个不能被覆盖的全局 marker
。
marker
does not resolve to a property of your map
object as your code seems to expect; instead, it resolves to a property of the global object. IE, however, populates the global object with properties whose names corresponding to the IDs of elements within the page and then doesn't allow you to overwrite these. This means that in IE there is already a global marker
that cannot be overwritten.
这是一个很好的理由应该避免像 marker
这样的隐含全局变量。最简单的解决方法是将引用改为 marker
到 this.marker
:
This is one good reason why implied globals like your marker
should be avoided. The easiest fix is to change references to marker
to this.marker
:
setPosition : function (x, y) {
this.marker.style.left = x + "px";
this.marker.style.top = y + "px";
},
init : function () {
this.marker = document.getElementById("marker");
this.setPosition(INITIAL_X, INITIAL_Y);
},
这篇关于IE7的CSS相对位置与Javascript错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!