jquery更改div的背景图片点击
I have 10 small pictures across the bottom of the screen and one main picture. What I am trying to achieve is having the main picture replaced by one of the 10 small pictures, when they are clicked on.
Code so far is:
$(function () {
$('#sp<?php echo $i; ?>').on {
'click', (function () {
$('#product-detail-pic').css('background-image', 'url(images/stock/<?php echo $stock[1][pic.$i]; ?>');
});
}
);
and the HTML/PHP is
<?php for($i=1;$i<6;$i++) {
if(($stock[1]['pic'.$i]!='')) { ?>
<div id="sp<?php echo $i; ?>" style="padding-right:13px; width:84px; height:61px; background:url(images/stock/<?php echo $stock[1]['pic'.$i]; ?>) no-repeat;float:left; background-size:84px 61px;">
<img src="images/zoom.png" width="40" height="30" />
</div>
<?php }
I don't recommend doing it this way as you need to bind the event handlers on each thumbnail, and that's not efficient. It's better if you put the thumbnail ID on the HTML tag instead of binding the click event on each thumbnail.
Your PHP code should look like this:
<?php
for( $i=1; $i<6; $i++ ) {
if( $stock[1]['pic'.$i] != '' ) { ?>
<div data-img-url="<?php echo $stock[1]['pic'.$i] ?>" style="padding-right:13px; width:84px; height:61px; background:url(images/stock/<?php echo $stock[1]['pic'.$i]; ?>) no-repeat;float:left; background-size:84px 61px;">
<img src="images/zoom.png" width="40" height="30" />
</div>
}
}
?>
and your jQuery event handler should look something like this:
$(function () {
$( '[data-img-url]' ).on( 'click', function () {
$('#product-detail-pic').css('background-image', $( this ).data( 'img-url' ) );
});
});
No messing with PHP on the JS side, much cleaner and efficient :)
I'm using '[data-img-url]'
as a jQuery selector just for this example. On your site, you should be using a selector that's relevant to the thumbnails.
For example, if your thumbnails are placed in a container with the thumbnails
ID, then you could do:
$( "#thumbnails" ).on( 'click', '[data-img-url]', function() {
$('#product-detail-pic').css('background-image', $( this ).data( 'img-url' ) );
} );
You are missing qoutes in $stock[1][pic.$i]
chnage like this,
$('#product-detail-pic').css('background-image','url(images/stock/<?php echo $stock[1]['pic'.$i]; ?>');
Try with
var imgId = '<?php echo $stock[1]["pic".$i]; ?>';
$('#product-detail-pic').css('background-image','url(images/stock/'+imgId+')');