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

首頁 > 編程 > JavaScript > 正文

分享一個原生的JavaScript拖動方法

2019-11-20 08:53:27
字體:
供稿:網(wǎng)友

代碼:

function drag(t,p){  var point = p || null,    target = t || null,    resultX = 0,    resultY = 0;  (!point)? point = target : ''; //如果沒有拖動點(diǎn),則拖動點(diǎn)默認(rèn)為整個別拖動元素  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': ''; //重置默認(rèn)位置。    (resultY >= maxHeight)?  target.style.top = maxHeight +'px' : (resultY > 0)?target.style.top = resultY +'px':''; //重置默認(rèn)位置。    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); //結(jié)果值是坐標(biāo)點(diǎn)減去被拖動元素距離瀏覽器左側(cè)的邊距        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(){  // 解決拖動時(shí),當(dāng)鼠標(biāo)指向的DOM對象非拖動點(diǎn)元素時(shí),無法觸發(fā)拖動點(diǎn)的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 表示拖動點(diǎn) */  // 注意:如果省略拖動點(diǎn),默認(rèn)可拖動的區(qū)域是整個被拖動元素

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 会同县| 鹤庆县| 松江区| 美姑县| 闸北区| 丽水市| 通河县| 璧山县| 金沙县| 柏乡县| 曲麻莱县| 桐梓县| 天峻县| 武功县| 青河县| 桃园市| 乐亭县| 新建县| 邵阳市| 建平县| 仙桃市| 万全县| 德庆县| 和林格尔县| 西乌| 浏阳市| 九江县| 芦山县| 鹤山市| 清丰县| 肥城市| 綦江县| 凤台县| 长宁县| 龙胜| 昌乐县| 禄丰县| 孝感市| 兴仁县| 城口县| 象州县|