繁体   English   中英

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

[英]JavaScript Absolute Positioning Not working in IE7

我尝试使用绝对定位来定位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放到左侧,然后将它们堆叠在彼此的顶部。 谁能给我一个为什么这不起作用的想法?

根据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 ,并且可以正常工作。


编辑2:

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

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

尝试直接分配样式,而不是通过setAttribute

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

难道你的答案是一样简单position:relative分配到body 由于父容器相对于其子容器的流动,您的div的行为方式似乎第二个被不同地定位。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM