拖动元素以特定°旋转它

时间:2015-05-30 00:59:38

标签: javascript jquery

http://codepen.io/kunokdev/pen/YXNrPx?editors=110

<div id="container">

  <div class="item-2"></div>
  <div class="item-2"></div>
  <div class="item-2"></div>
  <div class="item-2"></div>

</div>

body {
    background: #222;
}

#container {
 width: 300px;
 height: 300px;
 border-radius: 300px;
 background: #666;
 overflow: hidden;
}

.item-2 {
  float: left;
  background: blue;
  width: 50%;
  height: 150px;
 }
.item-2:nth-child(2){
  background: green;
 }
 .item-2:nth-child(3){
   background: yellow;
 }
.item-2:nth-child(4){
  background: red;
}

首先检查链接。所以,假设我有那个圆圈div。现在我想要的是一个简单的旋转它的功能。如果我们向右拖动它,它应该顺时针旋转。反之亦然。

1 个答案:

答案 0 :(得分:1)

我不确定此解决方案是否适用于移动设备,但这适用于浏览器:http://codepen.io/anon/pen/LVxzLj

var mouseX;
var currAngle = 0;
var container = document.getElementById("container");

container.addEventListener("mousedown",function(e){
  mouseX = e.pageX;
  window.addEventListener("mouseup",mouseup,false);
  window.addEventListener("mousemove",mousemove,false);
},false);

function mouseup(){
  currAngle = currAngle + e.pageX - mouseX;
  window.removeEventListener("mouseup",mouseup,false);
  window.removeEventListener("mousemove",mousemove,false);
}

function mousemove(e){
  var result = currAngle + e.pageX - mouseX;   
  container.style['transform'] = 'rotate(' + result + 'deg)';  
  container.style['-webkit-transform'] = 'rotate(' +  result + 'deg)';
  container.style['-moz-transform'] = 'rotate(' +  result + 'deg)';
}

另外,我添加了这个css,因为用户选择有一些奇怪的行为

#container {
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  user-select: none;
}