做了一個拖曳效果的例子就是點住指定的子元素區域 ?父元素隨著鼠標移動也跟隨移動,類似QQ登錄窗口點著上面一部分可以隨便拉到頁面任何一個地方但是我做出來基礎效果也有 但有一個問題就是我拖過一次放開鼠標后,再次點擊鼠標,一移動,元素就回到最開始的位置了,求好心人幫我看一下哪里出問題了 。以下是代碼;<!DOCTYPE?html>
<html>
<head>
????<meta?charset="UTF-8">
????<title>拖拽效果</title>
????<style>
????????body{
????????????position:?relative;
????????}
????????#box{
????????????width:?300px;
????????????height:?300px;
????????????background:?#666;
????????????position:?absolute;
????????}
????????#qq{
????????????width:?100px;
????????????height:?100px;
????????????position:?absolute;
????????????background:red;
????????????left:?100px;
????????}
????</style>
????
</head>
<body>
<div?id="box">
????<div?id="qq"></div>
</div>
</body>
</html>這里是JS<script?src="base庫.js"></script>
????<script>
????????//事件添加函數;
????????function?addEvent(element,type,callback){
????????????if(element.addEventListener){
????????????????element.addEventListener(type,callback,false);
????????????}else?if(element.attachEvent){
????????????????element.attachEvent('on'?+?type,callback)
????????????}
????????}
????????addEvent(window,"load",drag);
????????function?drag()?{
????????????var?oBox?=?document.getElementById("box");
????????????var?oQQ?=?document.getElementById("qq");
????????????addEvent(oQQ,?"mousedown",?fnDown);
????????????function?fnDown(evt)?{
????????????????var?e?=?evt?||?window.event;
????????????????//鼠標摁下時光標和面板之間的距離
????????????????var?disX?=?e.clientX,
????????????????????????disY?=?e.clientY;
????????????????//移動
????????????????document.onmousemove?=?function?(evt)?{
????????????????????var?e?=?evt?||?window.event;
????????????????????fnMove(evt,?disX,?disY);
????????????????};
????????????????//光標放開
????????????????document.onmouseup?=?function?()?{
????????????????????document.onmousemove?=?null;
????????????????????document.onmouseup?=?null;
????????????????};
????????????}
????????????function?fnMove(evt,?poxX,?poxY)?{
????????????????var?e?=?evt?||?window.event,
????????????????????????l?=?e.clientX?-?poxX,
????????????????????????t?=?e.clientY?-?poxY,
????????????????????????winW?=?document.documentElement.clientWidth?||?document.body.clientWidth,
????????????????????????winH?=?document.documentElement.clientHeight?||?document.body.clientHeight,
????????????????????????maxW?=?winW?-?oBox.offsetWidth,
????????????????????????maxH?=?winH?-?oBox.offsetHeight;
????????????????if?(l?<?0)?{
????????????????????l?=?0
????????????????}?else?if?(l?>?maxW)?{
????????????????????l?=?maxW
????????????????}
????????????????if?(t?<?0)?{
????????????????????t?=?0
????????????????}?else?if?(t?>?maxH)?{
????????????????????t?=?maxH
????????????????}
????????????????oBox.style.left?=?l?+?"px";
????????????????oBox.style.top?=?t?+?"px";
????????????}
????????}
????</script>
關于JS拖曳效果!求好心人幫忙解答!不勝感激!
Ni14
2016-12-30 22:35:53