I want to add one background url image to my css with jQuery. But nothing i've tried works.
let button = document.querySelector('form button.btn') button.addEventListener('click', () => { $(".img").css("background", "url('/images/Codax.jpg')"); })
div.img { height: 450px; width: 350px; background-color: #fff; -webkit-box-shadow: 7px 1px 15px 0px rgba(0, 0, 0, 0.55); -moz-box-shadow: 7px 1px 15px 0px rgba(0, 0, 0, 0.55); box-shadow: 7px 1px 15px 0px rgba(0, 0, 0, 0.55); background: url(''); background-position: center; background-repeat: no-repeat; background-size: cover; border-radius: 5px; }
<div class="perfil-img"> <div class="img"> </div> </div> <form> <button type="button" class="btn">Salvar</button> </form>
EDIT
Follow: In the link is the directories used in the project. Folders
This Html is called from a FetchContent. The desire is to add the image in html that FetchContent calls.
<li class="nav-item">
<a class="nav-link" href="#" a-view="infoPessoal" onclick="fetchContent(this)" a-folder="administrativo">
<i class="fas fa-user-tag"></i>
<!-- Icones -->
Pesssoal
</a>
</li>
Use ../images/Codax.jpg
the file path of the image should be relative to the location of the css file. You need to go up 1 dir by using ../
.
$(".img").css("background", "url('../images/Codax.jpg')")
For the sake of separation of concerns, i'll recommend you to create a CSS class with the corresponding background image set, then toggle the class using the .toggleClass() Method ie CSS should look like :
.background{
background : url('http://lorempixel.com/400/200');
width : 100%
/*Whatever other parameter*/
}
Js :
$( "button" ).click(function() {
$(".img").toggleClass( "background" );
});
This should work.
在这一行中使用background-image
而不仅仅是background
$(".img").css("background-image", "url('/images/Codax.jpg')");
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.