简体   繁体   中英

IE7 css block relative position with Javascript bug

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM