无法使用JavaScript中的全局样式表获得左侧位置
我需要获取JavaScript中图像的左上角位置。我定义图像在全局样式表中的位置:无法使用JavaScript中的全局样式表获得左侧位置,javascript,stylesheet,position,Javascript,Stylesheet,Position,我需要获取JavaScript中图像的左上角位置。我定义图像在全局样式表中的位置: <style type="text/css"> img.movable { position:relative; top:0px; left:375px; } </style> 但当我使用内联样式定义图像时: <img id="image11" style="position:relative; top:0px; left:375px;" src="logo.jpg" onclic
<style type="text/css">
img.movable { position:relative; top:0px; left:375px; }
</style>
但当我使用内联样式定义图像时:
<img id="image11" style="position:relative; top:0px; left:375px;" src="logo.jpg" onclick="jump()" />
style.left包含一个值
IE8和Firefox的这种行为是相同的。你知道为什么吗
干杯
Martin.el.style实际上是使用style属性应用的所有css属性的映射。要获取样式表或默认浏览器样式中定义的样式,需要使用计算样式 表示您指定的IMG标记的DOM元素有自己的style属性,其值将覆盖globals给定的任何值。不幸的是,在这种情况下,您指定的元素的属性实际上是空的,因为这些值不会级联到JavaScript对象级别
您需要从offsetLeft属性或CSS规则本身获取位置。。样式属性仅与内联CSS相关。因此,样式表中指定的样式将不会出现在.style列表中。如果要获取元素在页面上相对于视口的位置,应使用以下方法:
function getNodePosition(node) {
var top = left = 0;
while (node) {
if (node.tagName) {
top = top + node.offsetTop;
left = left + node.offsetLeft;
node = node.offsetParent;
} else {
node = node.parentNode;
}
}
return [top, left];
}
根据怪癖模式改编。OffsetTop和OffsetLeft是wrt到父级的,因此这将在树上迭代以获得总偏移量,从而获得页面位置。如果您想知道视口的位置,可以通过滚动距离调整此处返回的值。获取给定HTMLElement的左元素
function getHTMLElementLeft(HTMLElement, left)
{
if (left == undefined)
{
var left = 0;
}
if (HTMLElement.nodeType == 1)
{
left += HTMLElement.offsetLeft;
if (HTMLElement.offsetParent)
{
left = getHTMLElementLeft(HTMLElement.offsetParent, left);
}
}
return left;
}
+1用于链接。函数getStyleel,styleProp解决了我的问题。谢谢
function getNodePosition(node) {
var top = left = 0;
while (node) {
if (node.tagName) {
top = top + node.offsetTop;
left = left + node.offsetLeft;
node = node.offsetParent;
} else {
node = node.parentNode;
}
}
return [top, left];
}
function getHTMLElementLeft(HTMLElement, left)
{
if (left == undefined)
{
var left = 0;
}
if (HTMLElement.nodeType == 1)
{
left += HTMLElement.offsetLeft;
if (HTMLElement.offsetParent)
{
left = getHTMLElementLeft(HTMLElement.offsetParent, left);
}
}
return left;
}