栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

自己封装的一个原生JS拖动方法(推荐)

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

自己封装的一个原生JS拖动方法(推荐)

代码:

function drag(t,p){

  var point = p || null,
    target = t || null,
    resultX = 0,
    resultY = 0;

  (!point)? point = target : ''; //如果没有拖动点,则拖动点默认为整个别拖动元素

  function getPos(t){
    var offsetLeft = 0,
      offsetTop = 0,
      offsetParent = t;

    while(offsetParent){
      offsetLeft+=offsetParent.offsetLeft;
      offsetTop+=offsetParent.offsetTop;
      offsetParent = offsetParent.offsetParent;
    }

    return {'top':offsetTop,'left':offsetLeft};
  }

  function core(){

    var width = document.body.clientWidth || document.documentElement.clientWidth,
      height = document.body.clientHeight || document.documentElement.clientHeight; 
      maxWidth = width - target.offsetWidth,
      maxHeight = height - target.offsetHeight;

    (resultX >= maxWidth)? target.style.left = maxWidth+'px' : (resultX > 0)?target.style.left = resultX +'px': ''; //重置默认位置。
    (resultY >= maxHeight)?  target.style.top = maxHeight +'px' : (resultY > 0)?target.style.top = resultY +'px':''; //重置默认位置。

    point.onmousedown=function(e){  
      var e = e || window.event,
 coordX = e.clientX,
 coordY = e.clientY,
 posX = getPos(target).left,
 posY = getPos(target).top;

      point.setCapture && point.setCapture();  //将Mouse事件锁定到指定元素上。
      document.onmousemove=function(e){

 var ev = e || window.event,
   moveX = ev.clientX,
   moveY = ev.clientY;

 resultX = moveX - (coordX - posX); //结果值是坐标点减去被拖动元素距离浏览器左侧的边距
 resultY = moveY - (coordY - posY);

 (resultX > 0 )?((resultX < maxWidth)?target.style.left = resultX+'px' : target.style.left = maxWidth+'px') : target.style.left = '0px'; 
 (resultY > 0 )?((resultY < maxHeight)?target.style.top = resultY+'px' : target.style.top = maxHeight+'px') : target.style.top = '0px'; 

 ev.stopPropagation && ev.stopPropagation(); 
 ev.preventDefault;
 ev.returnValue = false;
 ev.cancelBubble = true;
      };
    };
    document.onmouseup=function(){  // 解决拖动时,当鼠标指向的DOM对象非拖动点元素时,无法触发拖动点的onmousedown的BUG。
      document.onmousemove = null;  
      point.releaseCapture && point.releaseCapture();  // 将Mouse事件从指定元素上移除。
    };
    point.onmouseup=function(e){
      var e = e || window.event;
      document.onmousemove = null;
      point.releaseCapture && point.releaseCapture();
    };
  }
  core();
  window.onresize = core;  
}

使用方式:

drag(t,p)


// 注意:如果省略拖动点,默认可拖动的区域是整个被拖动元素

以上就是小编为大家带来的自己封装的一个原生JS拖动方法(推荐)全部内容了,希望大家多多支持考高分网~

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/92649.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号