元素跟随鼠标移动

在前一篇里写了一个移动端的移动和碰撞的小例子,这一次来写写PC端的。代码其实差不多

①首先我们在页面中创造一个div。可移动的一个块<div id="box"></div>

②引入jquery.min.js

③css样式,要注意的是这个元素身上一定要生成绝对定位元素,给left/top值

④开始写事件

逻辑1.鼠标点击,获取落下的坐标

  2.移动时,鼠标落下的坐标不变,left/top值跟随鼠标移动改变数值。同时确保元素不可超过可见区域

  3.鼠标松开,位置不变

js代码

var $left,$top;
window.onload=function(){
// 手指点击事件
  $("#box").on("mousedown",function(e){
    var ev= e||window.event;
    var target = ev.target;
    $left =ev.clientX - target.offsetLeft;//鼠标当前点击的X点-元素距离屏幕的位置=鼠标在元素上的位置
    $top = ev.clientY - target.offsetTop;
    $(document).bind('mousemove', function (e) {
      var ev= e||window.event;
      var oLeft = ev.clientX - $left;//鼠标当前点击的X点-鼠标在元素的位置= 距离元素的位置
      var oTop = ev.clientY - $top;
      // 判断鼠标移动的距离限制不得超出可视区域
      if(oLeft <= 0) {
        oLeft = 0;
      }
      if (oTop <= 0) {
        oTop = 0;
      }
      if(oLeft > document.documentElement.clientWidth -$("#box").outerWidth()) {
        oLeft = document.documentElement.clientWidth- $("#box").outerWidth();
      }
      if(oTop > document.documentElement.clientHeight - $("#box").outerHeight()){
        oTop = document.documentElement.clientHeight - $("#box").outerHeight();
      }

      $("#box").css({
        "left": oLeft+"px",
        "top":oTop+"px"
      });
    })
  })
  $(document).on('mouseup',function () {
    $(this).unbind('mousemove')
  })

}

 

posted on 2018-06-12 10:14  Nichkhunnie  阅读(152)  评论(0编辑  收藏  举报

导航