JavaScript单击时交换/更改图像

时间:2011-11-28 07:08:08

标签: javascript image

我想更改下面用于将图像更改为链接/图像的按钮。任何帮助,将不胜感激!感谢。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style>
</style>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type='text/javascript'>
onload = function() {
    var buttonData = [
        {src:'fareast.gif',    href:'http://google.com'},
        {src:'middlearth.jpg', href:'http://yahoo.com'},
        {src:'europe.jpg',     href:'http://chappo.cc'}
    ];
    var $im1 = $("[name='im1']").click(function(){ window.open($(this).attr('href')); });
    $(".imgSwap").each(function(i) {
        var $b = $(this), d = buttonData[i] || buttonData[buttonData.length-1];
        $b.click(function() { $im1.attr({src:d.src,title:$(this).html(),href:d.href}); });
        if(i==0) { $b.click(); }
    });
};
</script>
</head>

<body>

<img name="im1" height="300" width="300" /><br/>
<button class="imgSwap">Far East</button>
<button class="imgSwap">Middle Earth</button>
<button class="imgSwap">Europe</button>
</body>
</html>

请帮助!

2 个答案:

答案 0 :(得分:2)

首先,HTML:

<a href="#" class="imgSwap"><img src="path/to/image/far_east_button.gif" class="buttonImage" /></a>
<a href="#" class="imgSwap"><img src="path/to/image/middle_earth.gif" class="buttonImage" /></a>
<a href="#" class="imgSwap"><img src="path/to/image/europe.gif" class="buttonImage" /></a>

然后,buttonData:

var buttonData = [
    //titles added
    {src:'fareast.gif',    href:'http://google.com', title:'Far East'},
    {src:'middlearth.jpg', href:'http://yahoo.com',  title:'Middle Earth'},
    {src:'europe.jpg',     href:'http://chappo.cc',  title:'Europe'}
];

然后,点击处理程序:

$(".imgSwap").each(function(i) {
var $b = $(this), d = buttonData[i] || buttonData[buttonData.length-1];
$b.click(function() {
    $im1.attr({src:d.src, title:d.title, href:d.href});//note change to composition of title
    return false;//Added to suppresses default hyperlink action of <a> links.
}).attr('title', d.title);
if(i==0) { $b.click(); }
});

希望这能解决问题。

答案 1 :(得分:2)

这样做

<script>
 function changeImg(val)
{
  if(val == 1)
{
 document.getElementById('im1').src = "fareast.gif";
}
if(val == 2)
{ document.getElementById('im1').src = "middlearth.jpg";}
if(val == 3)
{ document.getElementById('im1').src = "europe.jpg";}
}

</script>

<img name="im1" id='im1' height="300" width="300" /><br/>
<button class="imgSwap" onclick="changeImg('1');">Far East</button>
<button class="imgSwap" onclick="changeImg('2');">Middle Earth</button>
<button class="imgSwap" onclick="{changeImg('3');">Europe</button>