前几天在群里的看到一个朋友再发这个需求,就问一了一下我怎么弄,刚拿到这个粗略的考虑了一下,觉得需要角度,位置信息很麻烦,写起来需要不少时间,后来去网上查了一下Math的所有函数,希望能找到一个好的解决方案,还真找到了一个方案。
下面是html代码:
<div class="main-count">
<div class="clockCenter">
<div class="clockBg"></div>
<div class="clockNeedle">v</div>
</div>
</div>
你没看错,DOM元素就是这么少。。。
下面是css
*{ margin: 0; padding: 0;}
.clockCenter{ position: relative; width: 0; height: 0; margin: 300px 400px;}
.main-count{ width: 1200px; margin: 0 auto;}
.clockBg{ position: absolute; top: -151px; left: -151px; width: 300px; height: 300px; border: 1px cornflowerblue solid; border-radius: 50%;}
.clockNeedle{ position: absolute; left: 0; top: -151px; width: 15px; height: 15px; text-align: center; line-height: 15px; color: #666; background-color: #fff; border: 1px cornflowerblue solid; border-radius: 50%; transform: translate(-50%,-50%); cursor: pointer;}
DOM元素少,所以相应的样式就少的可怜了。。。。
下面是js,也不多:
var clockRest={
param:{},//用于存放传入的参数
area:1,//用于标记鼠标所在的区域
roundCount:0,//用于标记当前的圈数
canMove:false,//用于标记是否可以滑动
ClockCenter:document.getElementsByClassName("clockCenter").item(0),
clockNeedle:document.getElementsByClassName("clockNeedle").item(0),
centerPoint:{},
deg:0,
initFunc:function(option){
var _this=this;
this.param=option;
this.centerPoint=this.ClockCenter.getBoundingClientRect();
this.clockNeedle.addEventListener("mousedown",function(e){
_this.canMove=true;
});
document.addEventListener("mousemove",function(e){
var ev = e||window.event;
if(ev.preventDefault){
ev.preventDefault();
}else{
ev.stopPropagation();
}
if(!_this.canMove){
return false;
}
if(ev.pageX-_this.centerPoint.left<=0&&_this.area==1){
return false;
}else{
_this.deg = Math.atan2(((_this.centerPoint.top+window.scrollY)-ev.pageY),(ev.pageX-_this.centerPoint.left));
if(_this.deg*180/Math.PI>=0&&_this.deg*180/Math.PI<90){
_this.area=1;
}else if(_this.deg*180/Math.PI>=90&&_this.deg*180/Math.PI<180){
_this.area=4;
}else if(_this.deg*180/Math.PI<0&&_this.deg*180/Math.PI>=-90){
_this.area=2;
}else if(_this.deg*180/Math.PI<-90&&_this.deg*180/Math.PI>=-180){
_this.area=3;
}
_this.renderNeedle();
}
});
document.addEventListener("mouseup",function(e){
if(!_this.canMove){
return false;
}
_this.canMove=false;
});
},
renderNeedle:function(){
this.clockNeedle.style.top = -151*Math.sin(this.deg)+"px";
this.clockNeedle.style.left = 151*Math.cos(this.deg)+"px";
this.clockNeedle.style.transform=" translate(-50%,-50%) rotate("+(this.deg*180/Math.PI>0?(90-this.deg*180/Math.PI):(90-this.deg*180/Math.PI))+"deg)"
}
};
clockRest.initFunc({});
js总共也才几十行,因为还有很多位置因素未处理,我这边留了一个option的参数作为我们传入的一个接口,如果以后需要改动的时候可以比较方便的拓展。
最终实现的效果是可以拖动小三角做圆周运动。。。