Why is element.style.left returning NaN?

不问归期 提交于 2019-12-11 17:12:29

问题


I'm getting a weird error where in Internet Explorer 7, when I call Math.round on a float it gives me an "Invalid Argument" error. Consider the following:

var elementLeft = parseInt(element.style.left); // Here we're actually getting NaN
function Foo(x) {
  this.x = x;

  this.apply = function(element) {
    element.style.left = Math.round(this.x) + 'px';
  };
}
Foo(elementLeft);

In this case x is a non-negative number and element is just a DOM element in my page (a div, in fact).

Any ideas?

EDIT: The variable passed in as the x parameter is actually initialized earlier as parseInt(element.style.left). It appears that the first time I try to read element.style.left, IE is actually giving back NaN. I have updated the code to reflect this. Anyone know any workarounds for this?


回答1:


It appears that the first time I try to read element.style.left, IE is actually giving back NaN.

The first time you read element.style.left, is there actually any left style set on the element? Remember element.style only reflects style properties set in the inline style="..." attribute and not those applied by stylesheets.

If you haven't set an inline style, style.left will give you the undefined object, which does indeed parseInt to NaN.




回答2:


Is IE defaulting x to a bad value?

Scroll down to Item 10 on this page:

Everything was working fine in Firefox, Google Chrome etal. But I was having problems with IE (of all flavours). No selection tool would be presented and a javascript warning was produced which told me about an 'Invalid argument' being submitted to the Math.round function.

The cause was that when you first click on the image to start your selection, the scaleX and scaleY variables in the javascript on the page result in a value of Infinity. Firefox and every other browser seems to silently step over this and carry on processing as normal. IE of course did not.

The solution was to add the following line after the initial scaleX and scaleY variables are calculated. This appears to have solved the problem fully. if(scaleX == Infinity || scaleY == Infinity) return false; I hope this helps someone else and saves them the hour of hunting it cost me ;o)




回答3:


I don't think it's Math.round() that's giving you the error. It's probably the CSS subsystem. Try an alert() on the value that you're getting.




回答4:


Some frameworks such as jQuery have facilities to read the calculated position of elements -- without requiring you to have explicitly set CSS position properties on them. Try reading the position of your element through jQuery. It might work.



来源:https://stackoverflow.com/questions/1428268/why-is-element-style-left-returning-nan

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