简体   繁体   中英

Why am I getting insanely high values for left value of position()?

The relevant piece of code is

    this.place = function ()
    {
        var headElem = game.snake.links[0];
        this.bub.css({
            left: headElem.pos.x * game.blockWidth + $('#snake-board-column').css('padding-left'),
            bottom: headElem.pos.y * game.blockWidth
        });
        console.log(this.bub.position()); // TEST
    }

and the intent of it is to make a word bubble position relative to an SVG rect element (If you're wondering why I don't simply use CSS, it's because there's a lot of swapping/replacing of elements due to the game logic). The above function is invoked on page load and when the window resizes. What I'm finding strange is that the result of my test

console.log(this.bub.position()); // TEST

is sometimes producing very high values for left when the window is resized, and as a result the word bubble is off the screen. I just resized the window and got

Objectleft: 308.5top: 0__proto__: Object
game.js:290 Objectleft: 23515top: 0__proto__: Object
game.js:290 Object {top: 0, left: 23515}
game.js:290 Object {top: 0, left: 23515}
game.js:290 Object {top: 0, left: 23515}
game.js:290 Object {top: 0, left: 23515}
game.js:290 Object {top: 0, left: 23515}
game.js:290 Object {top: 0, left: 23515}
game.js:290 Object {top: 0, left: 23515}
game.js:290 Object {top: 0, left: 169169}
game.js:290 Object {top: 0, left: 169169}
game.js:290 Object {top: 0, left: 169169}

where you can see the first value for left is 308.5 (normal, expected) and the subsequent values are out of whack. You can see it in action here and the full JS here . Any idea what is causing this nonsense????

The strangest thing is that I've tested the individual values

headElem.pos.x , game.blockWidth and $('#snake-board-column').css('padding-left') and they all seem normal.

You may be concatenating strings instead of adding integers.

What is the type of headElem.pos.x , game.blockWidth and $('#snake-board-column').css('padding-left') ?

For example, I tried this in the console:

var paddingLeft = $('#snake-board-column').css('padding-left');
>> typeof paddingLeft
>> 'string'

Try parseInt() before summing the values.

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