简体   繁体   中英

Changing IMG SRC with Javascript

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)

I think your page is refreshing by your click, change your links as :

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

Why not do something like this (haven't checked the syntax completly, so it could be faulty.

function FirstPic()
{
    var pic1 = document.getElementById("pic1"); 
    if (pic1 == typeof('undefined')) return;
    pic1.src = "newpicname.jpg";
}

Make sure you give the tags an ID attribute called pic1 and pic2 (instead of a name attribute) and give the image itself an 'onclick' attribute...

<img onclick='FirstPic()' id='pic1' src='image1.jpg' />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM