This article mainly introduces the method to achieve the effect of js clicking to switch pictures. Hope it helps friends in need.
js switching picture effect code example is as follows:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>js图片切换特效代码示例</title> <style> img { width: 640px; height: 214px; position: absolute; } </style> </head> <body> <script> var imgArr=[ "image/a.jpeg", "image/b.jpeg", "image/c.jpeg", "image/d.jpeg", "image/e.jpeg" ]; var position=0; var imgB=new Image(); imgB.src=imgArr[1]; imgB.id="imgB"; document.body.appendChild(imgB); var imgA=new Image(); imgA.src=imgArr[0]; imgA.id="imgA"; document.body.appendChild(imgA); imgA.style.opacity=1; imgA.addEventListener("click",clickHandler); var id=0; function clickHandler() { imgA.removeEventListener("click",clickHandler); id=setInterval(imgOpacity,30); setTimeout(changImage,3000) } function imgOpacity() { if(imgA.style.opacity==0){ clearInterval(id); imgA.style.opacity=1; if(position+1>4){ imgB.src=imgArr[0] }else{ imgB.src=imgArr[position+1] } return; } imgA.style.opacity-=0.01; } function changImage() { position++; if(position>4){ position=0; } imgA.src=imgArr[position]; imgA.addEventListener("click",clickHandler); } </script> </body> </html>
js switching picture effect idea steps: First create two new graphics, 2 pictures A and B. A is put in last, therefore, A is at the top. imgA.style.opacity=1; This sentence is very important. If this value is not set, the value will be 0 when called in the function. We only listened to click events for imgA.
When the top image is clicked, set a time interval function to execute imgOpacity every 30 milliseconds, and set a timer switch to execute changeImage after 3 seconds.
Let the transparency of picture A be reduced by 0.01 for each execution, 100 times, 30*100=3000 milliseconds. The picture will become transparent after 3 seconds. When it is transparent, we clear the event interval function clearInterval(id); clear the time interval, that is, we no longer execute it every 30 milliseconds. We reset its transparency to 1, and set the address of image B to be the next image.
When the image is clicked for 3 seconds, the changeImage function is executed. Let the current position be 1. Set the address of picture A to the next picture.
Introduction to relevant knowledge points:
position records the current image position
The above is a specific introduction to the effect of js clicking to switch images, which has certain The reference value, I hope it will be helpful to everyone.
The above is the detailed content of How to achieve image switching effect after clicking on the image using js? (code example). For more information, please follow other related articles on the PHP Chinese website!