如何在mousedown时按住鼠标指针位置

时间:2017-06-27 18:29:16

标签: javascript onmousedown pointerlock

是否有可能让鼠标指针位置冻结在mousedown上,我觉得这会限制抓取和鼠标离开可抓取区域的问题,我已经在很多其他游戏中多次看过这个功能,我希望你是谁阅读本文了解我建议的功能类型......

这是我的代码。如果有人解决了鼠标冻结问题,请随时更新...

var container=document.getElementById('container');
 bottom =3750;
 rightside = 1300 ;
 leftside = 0,
 topside=0;

 var selected = null, // Object of the element to be moved
 x_pos = 0, y_pos = 0, // Stores x & y coordinates of the mouse pointer
 x_elem = 0, y_elem = 0; // Stores top, left values (edge) of the element

// Will be called when user starts dragging an element
function _drag_init(elem) {
// Store the object of the element which needs to be moved
   selected = elem;
   x_elem = x_pos - selected.offsetLeft;
   y_elem = y_pos - selected.offsetTop;     
}

// Will be called when user dragging an element
function _move_elem(e) {
   x_pos = document.all ? window.event.clientX : e.pageX;
   y_pos = document.all ? window.event.clientY : e.pageY;

    if (x_pos-x_elem <=leftside){
       x_pos =leftside + x_elem;
    }

    if (x_pos >=rightside){
       x_pos =rightside-10;
    }

    if (y_pos-10 <=topside){ 
       y_pos=topside+10;
    }

    if (y_pos+380 >=bottom){ 
       y_pos=bottom-380;
    }

    if (selected !== null) {
       selected.style.left = (x_pos - x_elem) + 'px';
       selected.style.top = (y_pos - y_elem) + 'px';
    }   
}

// Destroy the object when we are done
function _destroy() {
    selected = null;
}

// Bind the functions...
  document.getElementById('frame1').onmousedown = function () {
  _drag_init(this);
  return false;
};

document.onmousemove = _move_elem;
document.onmouseup = _destroy;

0 个答案:

没有答案