使用Javascript更改IMG SRC [英] Changing IMG SRC with Javascript

查看:95
本文介绍了使用Javascript更改IMG SRC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是javascript的新手,虽然有很多更复杂的解决方案,但我不理解它们,希望我现在不需要这样做。



我有一张主图...

 < img src =main-picture.jpgname =Mainpic ID = 图像 > 

...我希望能够在点击两个缩略图中的一个时更改此图片。

 < a href =onclick =FirstPic()>< img src =replacement1.jpg name =pic1>< / a> 
< a href =onclick =SecPic()>< img src =replacement2.jpgname =pic2>< / a>

我认为我的javascript代码非常简单。我目前正在使用...

  function FirstPic(){
document.Mainpic.src = document.pic1 .src
返回
}

函数SecPic(){
document.Mainpic.src = document.pic2.src
返回
}

现在变量 正在改变,但它不是停留改变了。单击缩略图时,替换图片会在屏幕上闪烁,然后返回到原始的main-picture.jpg。



如何将更改永久更改为止点击不同的缩略图?



谢谢!

解决方案

我认为它正在翻转,因为你的页面正在重新加载。



如果你不希望在onclick之后激活href =值,你需要从你的onclick =返回false。 / p>

此外,您可以设置href =#以防万一。 #无处可去(不会重新加载页面)


I'm new at javascript and while there are many more complex solutions, I don't understand them and hope I don't have to at this point.

I have a main picture...

<img src="main-picture.jpg" name="Mainpic" id="image">

...and I want to be able to change this picture when I click on one of two thumbnails.

<a href="" onclick="FirstPic()"><img src="replacement1.jpg" name="pic1"></a>
<a href="" onclick="SecPic()"><img src="replacement2.jpg" name="pic2"></a>

My javascript code I thought would be super easy. I'm currently using...

function FirstPic(){
        document.Mainpic.src = document.pic1.src
        return
    }

function SecPic(){
        document.Mainpic.src = document.pic2.src
        return
    }

Now the variable is changing however it's not staying changed. When the thumbnail is clicked on, the replacement picture flashes on the screen and then it returns to the original main-picture.jpg.

How do I make the change permanent until a different thumbnail is clicked?

Thanks!

解决方案

I think it's flipping back because your page is reloading.

You need to return false from your onclick= if you don't want the href= value to activate after your onclick.

Also, you can set href="#" just in case. # goes nowhere (doesn't ever reload the page)

这篇关于使用Javascript更改IMG SRC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆