Supercharging our example website

本文介绍如何使用 JavaScript 实现网页上的图片点击切换效果。通过获取图片元素引用并设置点击事件,根据当前图片源路径来判断并更换为另一张图片。

 

Now we've gone over a few JavaScript basics, let's add a few cool basic features to our example site to give you some first idea of what is possible.

Adding an image changer

In this section we'll add another image to our site, and add some simple JavaScript to change between the two when the image is clicked on.

  1. First of all, find another image that you'd like to feature on your site. Make sure it is the same size as your first image, or as close as possible.
  2. Save the image in your images folder.
  3. Go to your main.js file, and enter the following JavaScript (if your hello world JavaScript is still there, delete it):
    var myImage = document.querySelector('img');
    
    myImage.onclick = function() {
        var mySrc = myImage.getAttribute('src');
        if(mySrc === 'images/firefox-icon.png') {
          myImage.setAttribute ('src','images/firefox2.png');
        } else {
          myImage.setAttribute ('src','images/firefox-icon.png');
        }
    }
     
    

      

  4. Save all files and load index.html in the browser. Now when you click the image, it should change to the other one!

So here, we are storing a reference to our image element in the myImage variable. Next, we make this variable's onclick event handler property equal to an anonymous function. Now, every time this image element is clicked:

  1. We retrieve the value of the image's src attribute.
  2. We use a conditional to check whether the src value is equal to the path to the original image:
    1. If it is, we change the src value to the path to the 2nd image, forcing the other image to be loaded inside the <image> element.
    2. If it isn't (meaning it must already have changed), we change the src value back to the original image path, to flip it back to how it was originally.

转载于:https://www.cnblogs.com/hephec/p/4601145.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值