简体   繁体   中英

Trouble changing css with javascript

I want to change the padding on my header so that it effectively is lowered onto the page. I have the following code which runs and does nothing:

function openPage() {
    var i, el = document.getElementById('headbar');
    for(i=0;i<30;i++) {
        el.style.paddingTop = el.style.paddingTop + 1;
    }
}

However, while trying to figure out why it wasn't working in the console I figured out that maybe it is because the padding must be written in pixels because the following works and changes the padding in the console:

document.getElementById('headbar').style.paddingTop='100px';

is there any way I could do this without Jquery and without having to make a substring and reconcatonating?

Pretty simple just do this:

for(i=0;i<30;i++) {
     var px = (el.style.paddingTop + 1) + "px";
     el.style.paddingTop = px;
}

Try appending px to the variable

 var fontSize = parseInt(el.style.paddingTop, 10);
 el.style.paddingTop = ( (!isNaN(fontSize) : fontSize : 0) + 1) + 'px';

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