如何让用户继续点击图像并更改图像

时间:2017-09-18 07:23:58

标签: javascript html css

这是我的javascript:它基本上允许用户点击第二张图像(温度计),它会变为略高的温度,同时,烧杯也会相应改变。如何让用户继续点击并使图像做出相应的响应?

        $(document).ready(function () {

            $("#image").click(function () {

                //when image is clicked, change image 

                var img2 = document.getElementById('image2');
                img2.src = "images/beaker1.png";
                var img = document.getElementById('image');
                img.src = "images/t1.png";

                return false;
            });

        });

Html文件:

                     

                    <div class="col-sm-6">
                        <img id="image2" src="images/beaker0.png" class="img-rounded">
                        <img src="images/saturated_percipitate_1.png" class="img-rounded">

                    </div> 

                    <div class="col-sm-6">
                        <p><b>Increase Temperature</b></p>
                        <img id="image" src="images/t0.png" class="img-rounded"/>
                        <p><b>Decrease Temperature</b></p>
                    </div> 
                </div>

2 个答案:

答案 0 :(得分:0)

将类 notSelected 添加到您的图片

<img id="image2" src="images/beaker0.png" class="img-rounded notSelected">

然后尝试切换此类并根据某个类添加 src 属性。这应该有效:

$("#image").on('click',function(){
    $("#image2").toggleClass("selected notSelected");

    // change image
    $("img.selected").attr('src','images/beaker1.png');
    $("img.notSelected").attr('src','images/t1.png');
});

希望这有帮助。

答案 1 :(得分:0)

如果我理解正确,也许这就是你要找的东西 我们的想法是使用计数器显示当前图像。

    $(document).ready(function () {

        var indexImage = 1;
        $("#image").click(function () {

            //check if thermometer is at max.
            if(indexImage > 13){  //13 is example maximum value.
                return false;
            }

            //when image is clicked, change image 
            var img2 = document.getElementById('image2');
            img2.src = "images/beaker" + indexImage + ".png";
            var img = document.getElementById('image');
            img.src = "images/t" + indexImage + ".png";

            indexImage++;
            return false;
        });

    });