简体   繁体   English

在DIV中更改Image onClick?

[英]Change Image onClick Within DIV?

I have a jsFiddle setup to where you will be able to click on the image to the left and when you do it changes the image, but when you click on the DIV as an entirety (expand-one) it does not swap the image out. 我有一个jsFiddle设置,您可以在其中单击左侧的图像,并在执行该操作时更改图像,但是当您整体单击DIV(展开一个)时,它不会将图像换出。

I want to be able to click on a DIV (as a whole) and swap out an image that is within the DIV without having only being able to click on just the image. 我希望能够单击一个DIV(作为一个整体)并交换出DIV中的图像,而不必仅单击图像。

You can view what I mean here: http://jsfiddle.net/5PDV5/1/ 您可以在这里查看我的意思: http : //jsfiddle.net/5PDV5/1/

Thank you all! 谢谢你们! :) :)

All you need to do is inside the click handler for the div change the image's src. 您需要做的就是在div的点击处理程序中更改图片的src。

jQuery('.expand-one').click(function(){
        jQuery('.content-one').slideToggle('fast');
        var img = $(this).find('img'),
            src = img.attr("src")
            alt = img.data("altsrc");
            img.attr("src",alt).data("altsrc",src);
    });
    jQuery('.expand-one').toggle(function() {
        jQuery('.content-one').slideDown('fast');
        }, function() {
        jQuery('.content-one').slideUp('fast');
    });

Also a more efficient method would be to use classes and background images so the code would read like: 还有一种更有效的方法是使用类和背景图像,因此代码如下所示:

HTML 的HTML

<div class="expand-one blue-icon"></div>

CSS 的CSS

.expand-one { margin-left: 5px } /* Margin of Icon Size */
.blue-icon { background-image: url('blue-icon.png'); }
.green-icon { background-image: url('green-icon.png'); }

JS JS

//This turns one off and the other on
$(this).toggleClass('blue-icon green-icon');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM