简体   繁体   中英

Add and Remove Class when a div is toggled

Hi i have a problem with my code, i have a menu and a map in my page, when the page loads the map has col-lg-10 col-md-10 col-sm-10 col-xs-10 , because my menu is open, when i close the menu i made that the map changes to col-lg-12 col-md-12 col-sm-12 col-xs-12 , and it works fine but when i reopen the menu it doesn't change the class to col-lg-10 col-md-10 col-sm-10 col-xs-10 .

This is the code that i tried

UPDATE

Thanks everyone for your answers, I've added the == but now it only puts the col-lg-10 class

 function MapSize() {
        var shown = document.getElementById("containerForm");
        var map = document.getElementById("containerMap");

        if (shown.style.display == "none") {

            map.className = "col-lg-12 col-md-12 col-sm-12 col-xs-12";


        } else if (shown.style.display == "block") {
            map.className += "col-lg-10 col-md-10 col-sm-10 col-xs-10";
        }
    }  

Thanks :)

You are using assignment operators in your if statement.

Instead of having

if (shown.style.display = "none")

it should be

if (shown.style.display == "none")

Assignment operator instead of comparison in your if:

 if (shown.style.display = "none") {

Use ==

function MapSize() {

        var shown = document.getElementById("containerForm");
        var map = document.getElementById("containerMap");

        if (shown.style.display == "none") {

            map.className = "col-lg-12 col-md-12 col-sm-12 col-xs-12";


        } else if (shown.style.display == "block") {
            map.className = "col-lg-10 col-md-10 col-sm-10 col-xs-10";
        }
    } 

There are more than 1 problems:

1) use === for equality check if (shown.style.display === "none") should be if (shown.style.display === "none")

2) When you do map.className = "col-lg-12 col-md-12 col-sm-12 col-xs-12"; Your old classes col-lg-10 col-md-10 col-sm-10 col-xs-10 is gone. You can open chrome dev tools to check the classname.

Use map.className += instead of map.className =

3)Is map.className.remove a function? Please open the dev tool to check for errors.

Try this way

function MapSize() {
    var shown = document.getElementById("containerForm");
    var map = document.getElementById("containerMap");

    map.className = (shown.style.display === "none") ? "col-lg-12" : "col-lg-10";
}  

BTW, in bootstrap 3 class "col-lg-12 col-md-12 col-sm-12 col-xs-12" is equal to "col-lg-12" for the case as well as "col-lg-10 col-md-10 col-sm-10 col-xs-10" equal to "col-lg-10"

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