简体   繁体   中英

Reposition <div> with Javascript

I am trying to reposition a div on the page depending on a certain condition.

if (somecondition)
    document.getElementById("Div1").setAttribute("style", "position: absolute; left:297px; top:882px; height: 30px; width: 181px; margin-top: 0px;");

It is not repositioning the div in the html below:

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

Other code in the if fires.

Can anyone help? Browser: IE8

Using setAttribute is unreliable if you want the change to be reflected in the document. Use Element.style instead:

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';

You only need to do

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

(of course you should cache the getELementById)

To use the CSS as a single string, you should set the Element.style.cssText property:

var element = document.getElementById("Div1");
element.style.cssText = "position: absolute; left:297px; top:882px; height: 30px; " +
                        "width: 181px; margin-top: 0px;";

Its working perfectly all right, check out the demo here .

HTML:

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

Javascript:

document.getElementById("Div1").setAttribute("style", "position: absolute; left:297px; top:82px; height: 30px; width: 181px; margin-top: 0px;");

Make two style classes and add two different positions to the classes. Then change the DIVs class if javascript condition is satisfied. Eg:

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

CSS Styles

.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>

try like

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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