/ / alterar a imagem de fundo ao clicar usando jquery - jquery

alterar imagem de fundo ao clicar usando jquery - jquery

Como mudo a imagem de fundo usando jQuery?

Deve mudar a imagem fornecida no meu HTML. A função deve ser dinâmica para alterar qualquer imagem quando chamada.

Respostas:

0 para resposta № 1

Digamos que você tenha o seguinte código ...

<div id="container">
<img src="/images/some location">
</div>

Você pode alterar a imagem com o seguinte código jquery ...

function change_image(){

$("#container").html("<img src="/images/some other image location">");

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Deixe-me saber se funciona.


0 para resposta № 2

Como você disse que é novo no jQuery, prestei atenção extra ao comentar o código. Você realmente não especificou como a imagem de fundo deve ser definida, então usei um evento de clique nas miniaturas.

O código:

// before doing our magic with jQuery,
// we must wait for the dom to be ready to be manipulated
$(document).ready(function () {

// listen for a click on any img inside the .images
$(".images img").on("click", function () {

// inside the event handlers callback, THIS refers to the img that was clicked
// here we save the src property of the clicked img to a variable
var imgSrc = $(this).prop("src");

changeBackgroundImg(imgSrc);
});

});

function changeBackgroundImg(imgSrc) {
// we can set any css property to an element with jQuerys .css()
$("body").css("background-image", "url(" + imgSrc + ")");
}

Aqui é um demonstração.

Links para documentação relacionada ao código: