简体   繁体   中英

Javascript when button onclick change element position

I'm trying to do a button that when clicked will change my div position, I already do this:

 function myFunctionkomp1() { document.getElementsByClassName("MyDiv")[0].style.top="300px"; } 
 <button onclick="myFunctionkomp1();" id="btnmenukomp"></button> <div class="MyDiv" style="position: relative;"></div> 

And it works, but the only problem is that when I will click a second time on it the margin top will go to 0 (default).

Can someone please help me ?

function myFunctionkomp1()
{
    if(document.getElementsByClassName("MyDiv")[0].style.top == '300px'){
        document.getElementsByClassName("MyDiv")[0].style.top="0px";    
    }else{
        document.getElementsByClassName("MyDiv")[0].style.top="300px";  
    }
}

I won't give you the code of how to do it, but a good approach would be to do a "toggle" that alters between top=0px and top=300px. That way the 1st click with go to top =300px, 2nd click will go to top=0px, 3rd click will go back to 300px, etc.

Add some kind of toggle functionality. Eg:

var top = document.getElementsByClassName("MyDiv")[0].style.top;
top = top === '300px' ? 0 : '300px';
document.getElementsByClassName("MyDiv")[0].style.top = top;

Here is a fiddle: https://jsfiddle.net/ubL3hx2w/

You need a toggle variable like this (there are shorter ways to do this but in order to illustrate what the code is doing I have written it this way:

<script>
var toggle=true;
function myFunctionkomp1()
{
    if(flip) { 
        document.getElementsByClassName("MyDiv")[0].style.top="300px";
        toggle=false;
    }
    else {
        document.getElementsByClassName("MyDiv")[0].style.marginTop="0px";
        toggle=true;
    }
}
</script>

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