简体   繁体   中英

javascript add/remove class from div id?

I have the following div:

<div id="locker"></div>

My Div Id uses the below css styling:

#locker{
          width:20px;
height:20px;
background-repeat: no-repeat;
background-size:15px 15px;
background-position:5px center;
-webkit-border-radius: 20px;
-moz-border-radius: 20px;
border-radius: 20px;
border-style:solid;
border-width:1px;
border-color:#fff;
padding:3px;
position:relative;
text-align: center;
margin:auto;
 filter: invert(75%);
    -webkit-filter: invert(75%);
    background-image: url('../images/padlock.png');


      }

I also have a class styling:

                  .locker2{ 
background-image: url('../images/key.png');
      }

when a user clicks on another div of mine I am running the below javascript and I want the background image of my Div 'locker' to change from the background image in #locker to the one in .locker2

Here's how I'm trying to do it:

<script>
    $('#edit').click(function(){
    $('input').prop('disabled', false);
    $('input').css("background", "transparent");
    $('#locker').removeClass('#locker').addClass("locker2");
    $('#submit').css("display", "block");
});
</script>

However the background image is not changing. Please can someone show me where I am going wrong? Thanks

locker is the id of the element not a class, so for styling purposes it is easier to change your structure to a class like

 $('#edit').click(function() { $('input').prop('disabled', false); $('input').css("background", "transparent"); $('#locker').removeClass('locker').addClass("locker2"); $('#submit').css("display", "block"); }); 
 #locker { width: 20px; height: 20px; background-repeat: no-repeat; background-size: 15px 15px; background-position: 5px center; -webkit-border-radius: 20px; -moz-border-radius: 20px; border-radius: 20px; border-style: solid; border-width: 1px; border-color: #fff; padding: 3px; position: relative; text-align: center; margin: auto; filter: invert(75%); -webkit-filter: invert(75%); } .locker { background-image: url('//placehold.it/32X32/ff0000'); } .locker2 { background-image: url('//placehold.it/32X32/ff00ff'); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button id="edit">Edit</button> <div id="locker" class="locker"></div> 

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