zoukankan      html  css  js  c++  java
  • js实现简单拖拽效果

    方法如下:

    1. var params = {

      left: 0,

    2. top: 0,

    3. currentX: 0,

    4. currentY: 0,

    5. flag: false

    6. };

    7. var getCss = function(o,key){

    8. return o.currentStyle? o.currentStyle[key] : document.defaultView.getComputedStyle(o,false)[key];

    9. };

    10. var startDrag = function(bar, target, callback){

    11. if(getCss(target, "left") !== "auto"){

    12. params.left = getCss(target, "left");

    13. }

    14. if(getCss(target, "top") !== "auto"){

    15. params.top = getCss(target, "top");

    16. }

    17. bar.onmousedown = function(event){

    18. params.flag = true;

    19. if(!event){

    20. event = window.event;

    21. bar.onselectstart = function(){

    22. return false;

    23. }

    24. }

    25. var e = event;

    26. params.currentX = e.clientX;

    27. params.currentY = e.clientY;

    28. };

    29. document.onmouseup = function(){

    30. params.flag = false;

    31. if(getCss(target, "left") !== "auto"){

    32. params.left = getCss(target, "left");

    33. }

    34. if(getCss(target, "top") !== "auto"){

    35. params.top = getCss(target, "top");

    36. }

    37. };

    38. document.onmousemove = function(event){

    39. var e = event ? event: window.event;

    40. if(params.flag){

    41. var nowX = e.clientX, nowY = e.clientY;

    42. var disX = nowX - params.currentX, disY = nowY - params.currentY;

    43. target.style.left = parseInt(params.left) + disX + "px";

    44. target.style.top = parseInt(params.top) + disY + "px";

    45. if (event.preventDefault) {

    46. event.preventDefault();

    47. }

    48. return false;

    49. }

    50. if (typeof callback == "function") {

    51. callback(parseInt(params.left) + disX, parseInt(params.top) + disY);

    52. }

    53. }

    54. };

     使用方法为
         startDrag("触发拖拽的对象","被拖拽的对象")
  • 相关阅读:
    学习WindowsPhone 2013/12/22
    spring-aop学习
    easymock+junit+spring学习·
    javaWeb实现文件上传与下载 (转)
    Java实现视频网站的视频上传、视频转码、视频关键帧抽图, 及视频播放功能
    jsp自定义标签
    listener监听器
    移植一个项目到本地的问题
    struts1拦截器
    eclipse开发 javafx(转)
  • 原文地址:https://www.cnblogs.com/NatChen/p/7809489.html
Copyright © 2011-2022 走看看