2018.7.2 如何用js实现点击图片切换为另一图片,再次点击恢复到原图片

<!DOCTYPE html>
<html lang="zh">

    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>Document</title>
        <script type="text/javascript">
            window.onload = function(){
                var fruit = document.getElementById('fruit');
                //图片地址 
                btn1.onclick = function(){
                    alert(fruit.getAttribute('src'));
                }
                
                //喜欢的水果
                btn2.onclick =function(){
                    var loves = document.getElementsByName('enjoy');
                    //alert(loves.length);
                    var str = "";
                    for(var i in loves){
                        if(loves[i].checked == true){
                            str +=loves[i].value+"\n"   
                        }
                    }
                    alert(str);
                }   
            }
            
            //图片改变
            function change(){
                var f = document.getElementById('fruit');
                    if(f.getAttribute('src')=='img/grape.jpg'){
                        f.src="img/fruit.jpg";
                    }else{
                        f.src="img/grape.jpg";
                    }
                }
        </script>
        
    </head>

    <body>
        <img src="img/fruit.jpg" alt="水果图片" id="fruit" />
        <h1 id="love">选择你喜欢的水果:</h1>
        <input name="enjoy" type="checkbox" value="apple" />苹果
        <input name="enjoy" type="checkbox" value="banana" />香蕉
        <input name="enjoy" type="checkbox" value="grape" />葡萄
        <input name="enjoy" type="checkbox" value="pear" />梨
        <input name="enjoy" type="checkbox" value="watermelon" />西瓜
        <br />
        <input name="btn" type="button" value="显示图片路径" id="btn1" />
        <br /><input name="btn" type="button" value="喜欢的水果" id="btn2" />
        <br /><input name="btn" type="button" value="改变图片" onclick="change()"  id="btn3"/>
    </body>
</html>

猜你喜欢

转载自www.cnblogs.com/qichunlin/p/9250237.html