搞个JS的旋转齿轮
1.滑动条:
由input:[type=range]标签实现,滑条的值作为齿轮旋转的速度(每秒转n圈)
2.转动效果:
使用 js控制齿轮图片的css样式 transform:rotate(角度deg) ,图片每次都是以最初的状态为参考对象旋转的,而不是以最近一次的状态旋转
3.setInterval:
setInterval(function,ms) 以毫秒为周期的定时函数,这里定时每10毫秒转一次图片 (定时1毫秒的误差有点大) 如图:
这是定时一毫秒的,实际7,8毫秒才转一次
这是定时10毫秒的,与定时的10毫秒没大差距
效果:
css:单纯居中
<style type="text/css">
#out{
margin: 0 auto;
text-align: center;
}
#tip{
padding-top:20px;
width: 200px;
margin: 0 auto;
}
input{
width: 200px;
}
img{
margin-top: 20px;
}
</style>
html:
<div id="out">
//滑动条,控制每秒转多少圈,最大max圈,数值间距0.2圈
<input type="range" max="20" min="0" value="0.2" step="0.2"><br>
//齿轮图片
<img src="./gear.png" width="200px">
</div>
//显示转动时的相关数据
<div id="tip">
</div>
js:
<script>
go=document.querySelector("input") //滑动条元素(对象)
wheel=document.querySelector("img") //齿轮元素(对象)
//go.value=0.4 设置滑动条初始值
console.log('go.value的类型:'+typeof go.value+' ')
//go.step=0.2 设置滑动条数值间距
x=0 //记录每次转动的角度
setInterval(function(){
if(x>360){
x=x-360 //避免x的值太大
}
// 360/100 :每秒转一圈-->每10毫秒转3.6度
x+=parseFloat(go.value)*360/100 //parseFloat(go.value)表示当前每秒几转
wheel.style.transform="rotate("+x+"deg)" //每次都时由最初状态旋转的
document.getElementById("tip").innerHTML
="滑条值: "+go.value+"<br/>每秒: "+1*go.value+"转<br/>整体旋转角度: "+x
},10) //定时周期设置1毫秒时误差太大,这里设置10毫秒
</script>