使用单选按钮更改图像

时间:2015-04-18 17:39:35

标签: javascript html html5 image radio-button

我试图弄清楚如何使用单选按钮将图像更改为不同的图像。我想使用javascript和html / css来实现这一点,但我的javascript并不是那么精致。

我知道他的这里有其他答案,但他们似乎主要涉及背景/ div和jQuery,但我并不太了解jQuery。

这是我的代码:

HTML:

<form action="" id="animals">
<input type="radio" id="bunnybutton" name="animal" value="bunny" onClick="changeSrc()">bunny<br>
<input type="radio" id="kittybutton" name="animal" value="kitty" onClick="changeSrc()">kitty
    </form>
<img src="https://pbs.twimg.com/profile_images/447374371917922304/P4BzupWu.jpeg" id="picture" width=600px>

JAVASCRIPT:

function changeSrc() {
    if (document.getElementById("bunnybutton").checked) {
    document.getElementById("picture").src = "https://pbs.twimg.com/profile_images/447374371917922304/P4BzupWu.jpeg";
    } else if (document.getElementById("kittybutton").checked) { 
    document.getElementById("picture").src = "http://cutewallpaperss.com/wp-content/uploads/2015/01/cute_cats__cats_picture_cute_wallpaperss_hd_for_mobile.jpg";
    }
}

1 个答案:

答案 0 :(得分:1)

在代码编辑器中,您的代码运行良好!

&#13;
&#13;
function changeSrc() {
    if (document.getElementById("bunnybutton").checked) {
    document.getElementById("picture").src = "https://pbs.twimg.com/profile_images/447374371917922304/P4BzupWu.jpeg";
    } else if (document.getElementById("kittybutton").checked) { 
    document.getElementById("picture").src = "http://cutewallpaperss.com/wp-content/uploads/2015/01/cute_cats__cats_picture_cute_wallpaperss_hd_for_mobile.jpg";
    }
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<form action="" id="animals">
<input type="radio" id="bunnybutton" name="animal" value="bunny" onClick="changeSrc()">bunny<br>
<input type="radio" id="kittybutton" name="animal" value="kitty" onClick="changeSrc()">kitty
    </form>
<img src="https://pbs.twimg.com/profile_images/447374371917922304/P4BzupWu.jpeg" id="picture" width=600px>
&#13;
&#13;
&#13;