jQuery实现点击开关图片切换

原型大概是这样的

5640239-1edae6e5c6e94ee5.png
image

需求:点击右侧的蓝色眼睛,会变成

关键代码:

/* 实现图片切换 */

$(".imgclick").toggle(function(){

$(this).attr("src","img/close.png");

},function(){

$(this).attr("src","img/open.png");

}).attr("src","img/open.png");

其实原理很简单,就是利用toggle的参数切换不同函数。
可以直接复制黏贴的demo

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title></title>
        <script src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
    </head>

    <body>
        <div>
            <img class="imgclick" src="img/close.png" />
        </div>

        <div>
            <img class="imgclick" src="img/close.png" />
        </div>
    </body>
    <script>
        /* 实现图片切换 */
        $(".imgclick").toggle(function() {
            $(this).attr("src", "img/close.png");
        }, function() {
            $(this).attr("src", "img/open.png");
        }).attr("src", "img/open.png");
    </script>

</html>

原文作者:祈澈姑娘
技术博客:https://www.jianshu.com/u/05f416aefbe1

90后前端妹子,爱编程,爱运营,爱折腾。
坚持总结工作中遇到的技术问题,坚持记录工作中所所思所见,欢迎大家一起探讨交流。

原文地址:https://www.cnblogs.com/ting6/p/9725844.html