使用Javascript重新定位<div>元素

3
我正在尝试根据特定条件重新定位页面上的一个div。
if (somecondition)
    document.getElementById("Div1").setAttribute("style", "position: absolute; left:297px; top:882px; height: 30px; width: 181px; margin-top: 0px;");

以下的 html 无法重新定位 div:

<div id="Div1" style="top:366px; left:134px; position:absolute; height: 30px; width: 175px;">

if语句中的其他代码也会被执行。

有人能帮忙吗? 浏览器:IE8


你正在使用哪个浏览器?@K1f1 - vusan
7个回答

7

如果您希望更改能够在文档中反映出来,使用setAttribute是不可靠的。请使用Element.style代替:

var el = document.getElementById('Div1');
el.style.position = 'absolute';
el.style.left = '397px';
el.style.top = '882px';
el.style.height = '30px';
el.style.width = '181px';
el.style.marginTop = '0px';

3

您只需要执行以下操作

document.getElementById("Div1").style.<some css property> = <some value>; // like
document.getElementById("Div1").style.left = "297px";
document.getElementById("Div1").style.top = "882px";

(当然你应该缓存getElementById)

2
要将CSS作为单个字符串使用,您应该设置Element.style.cssText属性:
var element = document.getElementById("Div1");
element.style.cssText = "position: absolute; left:297px; top:882px; height: 30px; " +
                        "width: 181px; margin-top: 0px;";

2

它完美地工作得很好,可在这里查看演示

HTML:

<div id="Div1" style="top:366px; left:134px; position:absolute; height: 30px; width: 175px;">
    hello world
</div>

Javascript:

使用document.getElementById("Div1").setAttribute()方法可以设置元素的样式属性。在此代码中,我们将“Div1”元素的位置属性设置为绝对定位,左侧距离为297像素,顶部距离为82像素,高度为30像素,宽度为181像素,并将上边距设置为0像素。


2

创建两个样式类并为它们添加不同的位置。如果满足JavaScript条件,则更改DIV的类。例如:

if(someCondition) {
    document.getElementById('Div1').setAttribute('class', 'style2');
} else {
    document.getElementById('Div1').setAttribute('class', 'style1');
}

CSS 样式

.style1 {
    top:366px;
    left:134px;
    position:absolute;
    height: 30px;
    width: 175px;
}

.style2 {
    position: absolute;
    left:297px;
    top:882px;
    height: 30px;
    width: 181px;
    margin-top: 0px;

HTML

<div id="Div1" class="style1"></div>

1

尝试一下

document.getElementById("Div1").style.left = "297px";
document.getElementById("Div1").style.top = "882px";

0

你没有把 JavaScript 代码放在 document.ready(function(){}); 中吗?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接