简体   繁体   中英

Javascript style.left is empty string

next.onclick = function() { 
    move('left', li_items[0]);
};

var move = function(direction, el) {
    pos = el.style[direction].split('px')[0];
    pos = parseInt(pos, 10) + 10; 
    el.style[direction] = pos + 'px';
};

I'm using the simple code above to try and move an element. Now when I breakpoint on this, the value of el.style[direction] is: " " . So then when i try to do anything with it, it breaks. Why would this be? Isn't style.left supposed to return an integer?

Why would this be?

Presumably because it hasn't been set to anything.

Isn't style.left supposed to return an integer?

No. It is supposed to return a string containing the value of the CSS left property as set directly on the element (either by setting the JS property itself or by using a style attribute). It does not get a value from the cascade and it should only be an integer if the value is 0 (since all other lengths require units).

See How to get computed style of a HTMLElement if you want to get the computed value for the property rather than what I described in the previous paragraph.

style provides the original style as calculated from the CSS, not the updated and possibly dynamic style. You probably want currentStyle instead.

Just a comment.

In your code:

> pos = el.style[direction].split('px')[0];
> pos = parseInt(pos, 10) + 10;  

The split in the first line is superfluous, in the second line parseInt will convert (say) 10px to the number 10 just as effectively (and more efficiently) than what you have.

pos = parseInt(el.style[direction], 10);
next.onclick = function() { 
    move('left', li_items[0]);
};

var move = function(direction, el) {
    var lft = document.defaultView.getComputedStyle(el)[direction];
    pos = parseFloat(lft);
    pos = parseInt(pos, 10) + 10; 
    el.style[direction] = pos + 'px';
};

Note: like Elliot said you'll have to get the currentStyle/computedStyle. Here's a way to make it cross-browser, however when applying styles via JS, this is one good case where some sort of framework (eg Prototype [Scriptaculous], jQuery) would be useful.

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