国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > JS > 正文

自己封裝的一個原生JS拖動方法(推薦)

2024-05-06 16:33:02
字體:
來源:轉載
供稿:網友

代碼:

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)/*  * 說明  * t 表示被拖動的元素 * p 表示拖動點*/// 注意:如果省略拖動點,默認可拖動的區域是整個被拖動元素

以上就是小編為大家帶來的自己封裝的一個原生JS拖動方法(推薦)全部內容了,希望大家多多支持VeVb武林網~


注:相關教程知識閱讀請移步到JavaScript/Ajax教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 红安县| 邵武市| 永春县| 花莲县| 邯郸县| 长子县| 密云县| 额敏县| 吉安县| 六枝特区| 大庆市| 偃师市| 宣武区| 平阳县| 普陀区| 建昌县| 广宗县| 纳雍县| 新疆| 原阳县| 清原| 桐城市| 临夏县| 武宁县| 阆中市| 嘉荫县| 额尔古纳市| 晋州市| 工布江达县| 连南| 尼木县| 西安市| 鹤峰县| 肇庆市| 霞浦县| 敦煌市| 常熟市| 长葛市| 南江县| 双流县| 三台县|