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

Dev*_*xon 0 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);
Run Code Online (Sandbox Code Playgroud)

该脚本假设生成用户单击鼠标的div.但是在IE中它将div放在左侧,然后将它们叠加在一起.任何人都可以告诉我为什么这不起作用?

use*_*716 6

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

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';
Run Code Online (Sandbox Code Playgroud)

编辑:

它似乎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;');
}
Run Code Online (Sandbox Code Playgroud)

cssText在Chrome 10和Firefox 3.6中测试,它的工作原理.


EDIT2:

似乎对该属性有广泛的支持elem.style,因此您可能只想使用它而不是setAttribute().

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