简体   繁体   中英

How do I change the background of a button when clicked?

Okay, okay. I know many people have asked this question on Stack Overflow, but the solutions don't work for me. So my problem is simple: how do I make the female-av-button and male-av-button have a background URL of female-avatar & male-avatar respectively? Here's my code:

 body{ margin: 0; padding: 0; box-sizing: border-box; background-color: black; } .avatars{ justify-content: center; margin-left: 15%; display: flex; } .choose-a-user-text{ font-family: 'Luckiest Guy'; font-size: 400%; justify-content: center; } .choose-a-username{ margin-left: 25%; } .user-input{ margin-left: 29%; } .user-input:focus{ outline: none; } .female-av-button{ background: none; border: none; padding: 1px; } .female-av-button:focus{ } .male-av-button{ background: none; border: none; padding: 1px; } .female-av{ background: url('../img/female-avatar-silhouette.png') no-repeat; width: 500px; height: 700px; } .female-av:hover{ background: url('../img/female-avatar.png') no-repeat; width: 500px; height: 700px; } .male-av{ background: url("../img/male-avatar-silhouette.png") no-repeat; width: 500px; height: 700px; } .male-av:hover{ background: url("../img/male-avatar.png") no-repeat; width: 500px; height: 700px; }
 <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Choose Your Character</title> <link rel="stylesheet" href="css/avatar-page.css"> <link href="https://fonts.googleapis.com/css2?family=Luckiest+Guy&display=swap" rel="stylesheet"> </head> <body> <div class="choose-a-username"> <h2 class="choose-a-user-text" style="color: #018D94;">CHOOSE A USERNAME</h2> <input class="user-input" type="text" name="" value="" placeholder="username"> </div> <div class="avatars"> <button type="button" onclick="chooseanav()" class="female-av-button" name="button"><div class="female-av"></div></button> <button type="button" class="male-av-button" name="button"><div class="male-av"></div></button> </div> <!-- <div class="avatars"> <div class="silhos"> <img src="img/male-avatar-silhouette.png" class="avatar-silho" alt="male avatar silho"> <img src="img/female-avatar-silhouette.png" class="avatar-silho" alt="female avatar silho"> </div> <div class="avas"> <img src="img/male-avatar.png" class="avatar" alt="male avatar"> <img src="img/female-avatar.png" class="avatar" alt="female avatar"> </div> </div> --> <script type="text/javascript"> // document.getElementsByClassName("user-input").style.height="500px"; function chooseanav() { document.getElementsByClassName('female-av').style.background = "url('../img/female-avatar.png') no-repeat"; } </script> </body> </html>

Any help is greatly appreciated. Thanks!

Change your code to be;

document.getElementsByClassName('female-av')[0].style.background = "url('../img/female-avatar.png') no-repeat";

Oddly, unlike .getElementById() when you use .getElementsByClassName() you need to index the object. I think this is because IDs are unique where classes can be many.

The clue is in the getElement vs getElements .

EDIT: to answer your comment regarding clicking outside it etc you will have to change up your code a bit. Check my snippet below and let me know if anything doesn't make sense!

 body{ margin: 0; padding: 0; box-sizing: border-box; background-color: black; } .avatars{ justify-content: center; margin-left: 15%; display: flex; } .choose-a-user-text{ font-family: 'Luckiest Guy'; font-size: 400%; justify-content: center; } .choose-a-username{ margin-left: 25%; } .user-input{ margin-left: 29%; } .user-input:focus{ outline: none; } .female-av-button{ background: none; border: none; padding: 1px; } .female-av-button:focus{ } .male-av-button{ background: none; border: none; padding: 1px; } .female-av{ background: url('../img/female-avatar-silhouette.png') no-repeat; width: 500px; height: 700px; } .female-av:hover{ background: url('../img/female-avatar.png') no-repeat; width: 500px; height: 700px; } .male-av{ background: url("../img/male-avatar-silhouette.png") no-repeat; width: 500px; height: 700px; } .male-av:hover{ background: url("../img/male-avatar.png") no-repeat; width: 500px; height: 700px; }
 <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Choose Your Character</title> <link rel="stylesheet" href="css/avatar-page.css"> <link href="https://fonts.googleapis.com/css2?family=Luckiest+Guy&display=swap" rel="stylesheet"> </head> <body> <div class="choose-a-username"> <h2 class="choose-a-user-text" style="color: #018D94;">CHOOSE A USERNAME</h2> <input class="user-input" type="text" name="" value="" placeholder="username"> </div> <div class="avatars"> <button type="button" class="female-av-button" name="button"><div class="female-av"></div></button> <button type="button" class="male-av-button" name="button"><div class="male-av"></div></button> </div> <!-- <div class="avatars"> <div class="silhos"> <img src="img/male-avatar-silhouette.png" class="avatar-silho" alt="male avatar silho"> <img src="img/female-avatar-silhouette.png" class="avatar-silho" alt="female avatar silho"> </div> <div class="avas"> <img src="img/male-avatar.png" class="avatar" alt="male avatar"> <img src="img/female-avatar.png" class="avatar" alt="female avatar"> </div> </div> --> <script type="text/javascript"> var femaleAV = document.getElementsByClassName('female-av')[0]; var maleAV = document.getElementsByClassName('male-av')[0]; document.addEventListener('click', function(e) { if (e.target.className == 'female-av') { femaleAV.style.background = "url('../img/female-avatar.png') no-repeat"; maleAV.style.background = ""; } else if (e.target.className == 'male-av') { femaleAV.style.background = ""; maleAV.style.background = "url('../img/male-avatar.png') no-repeat"; } else { femaleAV.style.background = ""; maleAV.style.background = ""; } }); </script> </body> </html>

Basically, I have removed your onclick="" event from the female-av and have put an overall listener in the <script> . From here I have set 2 variables (Female & Male) and then an if-statement to check what is being clicked. Depending on what is being clicked it will either set/unset the female or male background respectively and if neither of the two are clicked it resets both.

There is a downside to this though, should the user click ANYWHERE else it means it will reset the selection. Example, if you select your MALE or FEMALE and then click to change your username you will see it deselects/resets.

To fix this, you can narrow the function like so;

document.querySelector('.avatars').addEventListener('click', function(e) {...})

That way it only listens to clicks inside the .avatars box.

I hope it's clear! If not, let me know and I'll try explain further!

You don`t have to use javascript to change it. You can use :focus directly in css.

.male-av:focus{
     background: url("../img/male-avatar.png") no-repeat;
     width: 500px;
     height: 700px;
}

.female-av:focus{
    background: url('../img/female-avatar.png') no-repeat;
    width: 500px;
    height: 700px;
}

So this way when the button is clicked you can keep the image or change the background color.But it returns to normal when clicked outside of the button.

This will make any element that has class female-av change its background on click

let fa = document.getElementsByClassName("female-av-button");
for(let i = 0;i<fa.length;i++){
    fa[i].addEventListener('click',function(){
        this.style.background="url('../img/female-avatar.png') no-repeat";
    });
}

if you want only one specific element to have this behavior give it an id and use

document.getElementById("elementID").addEventListener('click',function(){this.style.background="black";});

Maybe have the image contained in the button itself and not the CSS. Then have a JavaScript function that changes the image.

Or (the easier option) have a JS function that toggles the class containing the new image and the one with the old image (with the old image class already in there).

Say...

 <html> <style> /* add this to <style> the css (exept the image links) */ .confirm { background: url('https://live.staticflickr.com/7057/7119974123_291cac34b7_b.jpg') no-repeat; } .unclicked { background: url('https://upload.wikimedia.org/wikipedia/commons/thumb/8/84/Flag_of_Tabajd_%281-1_aspect_ratio%29.svg/480px-Flag_of_Tabajd_%281-1_aspect_ratio%29.svg.png') no-repeat; } </style> <script> /*add this to <script> block*/ function change() { var btnImg= document.getElementById("btn") btnImg.classList.toggle("confirm") btnImg.classList.toggle("unclicked") } </script> <div id="Copy this"></div> <button class="unclicked" id="btn" onClick=change()></button> </html>
The classes are so the background can be swapped and clicking it twice will result in the original image showing! It does work for me, so I hope this helps!


Gypsy.jpg location (uploaded)
This will work:
 //CSS button { background: blue; }
 <!-- HTML and JS --> <!-- Blue to Gypsy.jpg --> <button id="this" onclick="putimage('https://i.stack.imgur.com/8oMX9.jpg'); //<-- paste image here.">Click Me!</button> <script> var putimage = function(i) { // i is image url. document.getElementById("this").style = 'background: url("' + i + '") space !important'; }; </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