JavaScript绝对定位在IE7中不起作用

时间:2011-02-20 15:47:31

标签: javascript css internet-explorer

我尝试使用绝对定位来定位div,它在Safari和Firefox中工作正常,但在IE中失败,我无法弄清楚原因。代码是这样的:

var tempX=123;
var tempY=456;
var commentnum=3;
var bodyelement = document.getElementsByTagName('body')[0];
var newdiv = document.createElement('div');
newdiv.setAttribute('id', 'comment_text'+commentnum);
newdiv.setAttribute('style', 'text-align:center;z-index:10001;left:'+(tempX-23)+'px;top:'+(tempY-80)+'px;position:absolute;');
newdiv.innerHTML = commenthtml;
bodyelement.appendChild(newdiv);

该脚本假设生成用户单击鼠标的div。但是在IE中它将div放在左侧,然后将它们叠加在一起。谁能让我知道为什么这不起作用?

3 个答案:

答案 0 :(得分:6)

根据quirksmode,setAttribute不能用于在IE中设置style属性。

http://www.quirksmode.org/bugreports/archives/2005/03/setAttribute_does_not_work_in_IE_when_used_with_th.html

  

使用setAttribute,您应该能够在元素上设置任何属性。看来在IE中,尝试设置样式属性不起作用。

相反,您可能需要单独设置样式属性:

newdiv.style.textAlign = 'center';
newdiv.style.zIndex = 10001;
newdiv.style.left = (tempX-23) + 'px';
newdiv.style.top = (tempY-80) + 'px';
newdiv.style.position = 'absolute';

修改

似乎IE具有cssText属性。我不确定浏览器支持,但也许你可以测试它。

if( 'cssText' in newdiv.style ) {
    newdiv.style.cssText = 'text-align:center;z-index:10001;left:'+(tempX-23)+'px;top:'+(tempY-80)+'px;position:absolute;';
} else {
    newdiv.setAttribute('style', 'text-align:center;z-index:10001;left:'+(tempX-23)+'px;top:'+(tempY-80)+'px;position:absolute;');
}

在Chrome 10和Firefox 3.6中经过测试cssText,它可以正常运行。


EDIT2:

elem.style上的该属性似乎there's wide support,因此您可能只想使用它而不是setAttribute()

newdiv.style.cssText = 'text-align:center;z-index:10001;left:'+(tempX-23)+'px;top:'+(tempY-80)+'px;position:absolute;';

答案 1 :(得分:3)

尝试直接指定样式,而不是通过setAttribute

newdiv.style.position = "absolute";
newdiv.style.left = (tempX-23) + "px";
newdiv.style.top = (tempY-80) + "px";

答案 2 :(得分:0)

您的回答是否可以像分配给position:relative的{​​{1}}一样简单? 你的div的行为方式似乎是由于父容器相对于子容器的流动,第二种定位方式不同。