javascript拖拽效果延伸学习

1.实现拖拉图片时,带框的效果。即当鼠标拖动某一个图片或物体时,其原有位置扔保留其型。

这种效果,其实很简单,主要是另外创建一个物体,使其与被拖拽的物体,宽和高一样,然后,将其变为拖拽的对象。

直接上代码:

<html <head> <style> #div1 {width:100px; height:100px; background:yellow; position:absolute;} .box{border: 1px solid black;position: absolute;} </style> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <script> window.onload=function ()//凡是被拖拽的物体,其必须定位为absolute { var oDiv=document.getElementById('div1'); oDiv.onmousedown=function (ev) { var oEvent=ev||event; var disX=oEvent.clientX-oDiv.offsetLeft; var disY=oEvent.clientY-oDiv.offsetTop; var oNewDiv=document.createElement('div'); oNewDiv.className='box'; oNewDiv.style.width=oDiv.offsetWidth-2+'px';//将2px的边框去掉 oNewDiv.style.height=oDiv.offsetHeight-2+'px'; oNewDiv.style.left=oDiv.offsetLeft+'px'; oNewDiv.style.top=oDiv.offsetTop+'px'; document.body.appendChild(oNewDiv); document.onmousemove=function (ev) { var oEvent=ev||event; oNewDiv.style.left=oEvent.clientX-disX+'px'; oNewDiv.style.top=oEvent.clientY-disY+'px'; }; document.onmouseup=function () { document.onmousemove=null; document.onmouseup=null; document.body.removeChild(oNewDiv); oDiv.style.left=oNewDiv.style.left; oDiv.style.top=oNewDiv.style.top; }; }; }; </script> </head> <body> <div> </div> </body> </html>

2.关于窗口拖拉放大缩小的效果,就是在上面的div之中再包一个div。

<html <head> <style> #div1 {width:10px; height:10px; background:url(images/1.gif); position:absolute;bottom: 0;right: 0}//拖拉的物体,改为图片 #div2{width: 200px;height: 200px;position: relative;background: #ccc;} .box{border: 1px solid black;position: absolute;} </style> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <script> window.onload=function ()//凡是被拖拽的物体,其必须定位为absolute { var oDiv=document.getElementById('div1'); var oDiv2=document.getElementById('div2'); oDiv.onmousedown=function (ev) { var oEvent=ev||event; var disX=oEvent.clientX-oDiv.offsetLeft; var disY=oEvent.clientY-oDiv.offsetTop; var oNewDiv=document.createElement('div'); //oNewDiv.className='box'; oNewDiv.style.width=oDiv.offsetWidth-2+'px'; oNewDiv.style.height=oDiv.offsetHeight-2+'px'; oNewDiv.style.left=oDiv.offsetLeft+'px'; oNewDiv.style.top=oDiv.offsetTop+'px'; document.body.appendChild(oNewDiv); document.onmousemove=function (ev) { var oEvent=ev||event; oDiv2.style.width=oEvent.clientX-disX+'px';//这里是它的父级 oDiv2.style.height=oEvent.clientY-disY+'px'; }; document.onmouseup=function () { document.onmousemove=null; document.onmouseup=null; document.body.removeChild(oNewDiv); oDiv.style.left=oDiv2.style.left; oDiv.style.top=oDiv2.style.top; }; }; }; </script> </head> <body> <div> <div> </div> </div> </body> </html>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgyzpj.html