I'm trying to manipulate a div element. Although I have defined certain property values, I开发者_开发百科 can't seem to get the initial values.
Here's the problem: Fiddle
I'm at the end of my rope... Thanks.
I think you have to use document.styleSheets
, find your stylesheet, then loop through the cssRules(IE rules) list to match a selector to "#viewbase"
and then you can access your style properties like you would have with inline styles, since the style info in there is also a CSSStyleDeclaration ( so you can use element.style.left and so on).
Sidenode: getComputedStyle
doesn't work on most versions of IE. IE has currentStyle
properties for each element, but it's not the same thing. Maybe a combination of both will also work.
UPDATE
Managed to get the initial positions, if that's what you need, you can reassign these values if i remember well.
function trigger(e) {
item = this;
if (!e) var e = window.event;
if (e.pageX || e.pageY) {
x1 = e.pageX;
y1 = e.pageY;
}
else if (e.clientX || e.clientY) {
x1 = e.clientX;
y1 = e.clientY;
}
document.getElementById("ex").innerHTML = x1;
document.getElementById("wye").innerHTML= y1;
// the stylesheet you defined, in a standalone context, it might
// have another index, (i.e. 0 if it's the only one)
list = document.styleSheets[2].cssRules;
for(var i=0;i<list.length;i++)
//match #viewbase
if(list[i].selectorText.toLowerCase() == "#"+item.id)
{ item = list[i];
break;
}
document.getElementById("xval").innerHTML = item.style.left;
document.getElementById("yval").innerHTML = item.style.top;
document.getElementById("parseX").innerHTML = parseInt(item.style.left, 10);
document.getElementById("parseY").innerHTML = parseInt(item.style.top, 10);
document.getElementById("debug").innerHTML = 'clicked!';
document.onmouseup = release;
}
The other version would be to use the following
var styleDef = window.getComputedStyle(item) || item.currentStyle;
document.getElementById("xval").innerHTML = styleDef.left;
document.getElementById("yval").innerHTML = styleDef.top;
The problem is that your style is not defined within the html but comes from css. In that case you need to use getComputedStyle to retrieve the styling information. Do something like
document.defaultView.getComputedStyle(item,null)
rather than item.style.
How about using item.offsetLeft
and item.offsetTop
. This will include margins and padding, but you should be able to easily compensate for this fact. Here is an updated JSFiddle.
document.getElementById("xval").innerHTML = item.offsetLeft;
document.getElementById("yval").innerHTML = item.offsetTop;
Again, in this case, these calls return 10, 10
respectively, instead of 0, 0
, which you are looking for. That said, is this enough to move you past your issue?
精彩评论