dongyou6847 2014-02-21 11:51
浏览 146
已采纳

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 }
  • 写回答

3条回答 默认 最新

  • douyan6871 2014-02-21 15:30
    关注

    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' ) );
    } );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 如何实现uniapp编译的微信小程序做可回溯视频
  • ¥15 求Houdini使用行家,付费。价格面议。
  • ¥15 AttributeError: 'EasyDict' object has no attribute 'BACKUP_DB_INFO'
  • ¥15 前端高拍仪调用问题报错
  • ¥15 想用octave解决这个数学问题
  • ¥15 Centos新建的临时ip无法上网,如何解决?
  • ¥15 海康威视如何实现客户端软件对设备语音请求的处理。
  • ¥15 支付宝h5参数如何实现跳转
  • ¥15 MATLAB代码补全插值
  • ¥15 Typegoose 中如何使用 arrayFilters 筛选并更新深度嵌套的子文档数组信息