css + js实现图片不停旋转 鼠标悬停停止旋转

效果图如下动图所示:

效果图.gif

代码如下:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style>
			#img {
				border-radius: 50%;
				cursor: pointer;
				position: absolute;
				top: 50%;
				left: 50%;
				margin-top: -150px;
				margin-left: -150px;
			}
		</style>
		<script>
			var rotateVal = 0 // 旋转角度
			var InterVal // 定时器
			window.onload = function () {
				// 网页加载完成后即运行rotate函数
				rotate()
				// 鼠标悬浮在图片上时,停止旋转,即清除定时器
				document.getElementById('img').onmousemove = function () {
					clearInterval(InterVal)
				}
				// 鼠标离开图片时,继续旋转,即继续运行定时器
				document.getElementById('img').onmouseleave = function () {
					rotate()
				}
			}
			
			// 设置定时器
			function rotate () {
				InterVal = setInterval(function () {
					var img = document.getElementById('img')
					rotateVal += 1
					// 设置旋转属性(顺时针)
					img.style.transform = 'rotate(' + rotateVal + 'deg)'
					// 设置旋转属性(逆时针)
					//img.style.transform = 'rotate(-' + rotateVal + 'deg)'
					// 设置旋转时的动画  匀速0.1s
					img.style.transition = '0.1s linear'
				}, 100)
			}
		</script>
	</head>
	<body>
		<img id="img" src="images/111.jpg" width="300px" height="300px" />
	</body>
</html>

111.jpg文件:

111.jpg

猜你喜欢

转载自blog.csdn.net/u011295864/article/details/84773123