js实现拖拽改变dom元素大小

谁借莪1个温暖的怀抱¢ 2021-11-09 17:32 615阅读 0赞
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title></title>
  5. <style>
  6. #panel{
  7. position: absolute;
  8. width: 200px;height: 200px;
  9. background: green;
  10. }
  11. #dragIcon{
  12. position: absolute;bottom: 0;right: 0;
  13. width: 20px;height: 20px;
  14. background: yellow;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <div id="panel">
  20. <div id="dragIcon"></div>
  21. </div>
  22. <script>
  23. window.onload = function () {
  24. // 1. 获取两个大小div
  25. var oPanel = document.getElementById('panel');
  26. var oDragIcon = document.getElementById('dragIcon');
  27. // 定义4个变量
  28. var disX = 0;//鼠标按下时光标的X值
  29. var disY = 0;//鼠标按下时光标的Y值
  30. var disW = 0; //拖拽前div的宽
  31. var disH = 0; // 拖拽前div的高
  32. //3. 给小div加点击事件
  33. oDragIcon.onmousedown = function (ev) {
  34. var ev = ev || window.event;
  35. disX = ev.clientX; // 获取鼠标按下时光标x的值
  36. disY = ev.clientY; // 获取鼠标按下时光标Y的值
  37. disW = oPanel.offsetWidth; // 获取拖拽前div的宽
  38. disH = oPanel.offsetHeight; // 获取拖拽前div的高
  39. document.onmousemove = function (ev) {
  40. var ev = ev || window.event;
  41. //拖拽时为了对宽和高 限制一下范围,定义两个变量
  42. var W = ev.clientX - disX + disW;
  43. var H = ev.clientY - disY + disH;
  44. if(W<100){
  45. W = 100;
  46. }
  47. if(W>800){
  48. W =800;
  49. }
  50. if(H<100){
  51. H = 100;
  52. }
  53. if(H>500){
  54. H = 500;
  55. }
  56. oPanel.style.width =W +'px';// 拖拽后物体的宽
  57. oPanel.style.height = H +'px';// 拖拽后物体的高
  58. }
  59. document.onmouseup = function () {
  60. document.onmousemove = null;
  61. document.onmouseup = null;
  62. }
  63. }
  64. }
  65. </script>
  66. </body>
  67. </html>

发表评论

表情:
评论列表 (有 0 条评论,615人围观)

还没有评论,来说两句吧...

相关阅读

    相关 js

    拖拽使用的三个事件 onmousedown //鼠标按下 onmousemove //鼠标移动 onmouseup //鼠标抬起

    相关 JS

    实现后效果 ![70][] 实现原理: 1. 在允许拖拽的节点元素上,监听mousedown(按下鼠标按钮)事件,鼠标按下后,事件触发 2. 监听mousemov