如何更改图像onclick的JavaScript功能? [英] how to change image onclick javascript function?

查看:109
本文介绍了如何更改图像onclick的JavaScript功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个问题,我尝试过几次,但结果总是一样的,我不知道我的代码有什么问题。如果你点击右边的图像,它会变成左边的图像,但是如果你点击左边的图像,它不会变成正确的图像,为什么?
这里是代码:

$ p $ function changeImage(){

if(document.getElementById (changer)。src ==imgs / left.gif)
{
document.getElementById(changer)。src =imgs / right.gif;
}
else
{
document.getElementById(changer)。src =imgs / left.gif;
}

}

和image src代码在这里:

 < img src =imgs / right.gifid =changeronclick =changeImage()/> < / A> 

我需要这个函数:
点击(右箭头图片),然后它会更改为(左箭头图像)并再次点击相同(左箭头图像)将返回默认值,(右箭头图像)。



预先感谢您的时间和帮助。 正如Prabu在他的回答中所解释的那样,实际的src是绝对路径,但不是相对路径。为了解决这个问题:




  • 将元素对象(即 this )作为参数传递给函数。
  • 创建变量元素对象内的 bln ,例如该函数中的元素






 < img src =imgs /right.gifid =changeronclick =changeImage(this)/> 
^传递元素对象






  function changeImage(element){
element.src = element.bln? imgs / right.gif:imgs / left.gif;
element.bln =!element.bln; / *分配相反的布尔值总是* /
}

上述功能将切换图像src的取决于 src 属性中的值。
$ b 示例小提琴



顺便说一句,您也可以使用只是CSS:



工作小提琴


I got a problem, I tried several times but result is always same, I don't know what's wrong with my code. If you click on right image, it will change to left image, but if you click on left image, it wont change to right image, why? here is code:

    function changeImage() {

    if  (document.getElementById("changer").src == "imgs/left.gif")
    {
        document.getElementById("changer").src = "imgs/right.gif";
    }
    else 
    {
        document.getElementById("changer").src = "imgs/left.gif";
    }

}

and image src code here:

<img  src="imgs/right.gif" id="changer" onclick="changeImage()"/></a>

I need this function: click on (right arrow image), then it'll change to (left arrow image) and click on same (left arrow image) again will return to default, (right arrow image).

Thank you in advance for your time and help.

解决方案

As explained by Prabu in his answer that the actual src is absolute path but not relative path.

To solve this:

  • Pass the element object i.e this as argument to the function.
  • Create a variable bln inside the element object i.e element in that function.

<img src="imgs/right.gif" id="changer" onclick="changeImage(this)" />
                                                             ^ pass the element object             


 function changeImage(element) {
     element.src = element.bln ? "imgs/right.gif" : "imgs/left.gif";
     element.bln = !element.bln;  /* assigns opposite boolean value always */
 }

The above function will toggle the image src's without depending on the value present inside the src property.

Sample Fiddle

BTW, You can also do this using just CSS:

Working Fiddle

这篇关于如何更改图像onclick的JavaScript功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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