IE7 css block relative position with Javascript bug

£可爱£侵袭症+ 提交于 2019-12-13 02:59:57

问题


I have a simple JS script that moves a CSS block at a specific path when a value is given to it.

You can take a look at the code here http://jsfiddle.net/rayshinn/6DGfb/

This code seem to work fine on Chrome and Firefox except IE7.

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

Line 27 is as follows

    marker = document.getElementById("marker");
    this.setPosition(INITIAL_X, INITIAL_Y);

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!


回答1:


The problem is the line

marker = document.getElementById("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.

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);
    },


来源:https://stackoverflow.com/questions/16693598/ie7-css-block-relative-position-with-javascript-bug

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!