點選圖片播放暫停的demo
阿新 • • 發佈:2019-01-08
效果:
原始碼:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> .wp, .wp>img { width: 100px; height: 100px; border-radius: 100%; } .wp { margin: 0 auto; } .desc { margin: 20px auto 0; text-align: center; } .animate { animation: round 10s linear infinite; } @keyframes round { 100% { transform: rotate(1turn); } } </style> </head> <body> <div class="wp"> <img src="https://sfault-avatar.b0.upaiyun.com/408/449/4084493968-55c2142e12b21_huge256"> </div> <p class="desc">點選圖片播放/暫停</p> </body> <script> var isPlaying = false; var container = document.querySelector('.wp'); var image = container.querySelector('img'); image.addEventListener('click', function bindEvent() { isPlaying ? pause() : play(); }); function pause() { isPlaying = false; var iTransform = getComputedStyle(image).transform; var cTransform = getComputedStyle(container).transform; container.style.transform = cTransform === 'none' ? iTransform : iTransform.concat(' ', cTransform); image.classList.remove('animate'); } function play() { isPlaying = true; image.classList.add('animate'); } </script> </html>
直接複製貼上就能用