标签:
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.
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.
images
folder.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‘); } }
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:
src
attribute.src
value is equal to the path to the original image:src
value to the path to the 2nd image, forcing the other image to be loaded inside the <image>
element.src
value back to the original image path, to flip it back to how it was originally.Supercharging our example website
标签:
原文地址:http://www.cnblogs.com/hephec/p/4601145.html