欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

AngularJS实现的简单拖拽功能示例

程序员文章站 2022-09-04 07:58:53
本文实例讲述了angularjs实现的简单拖拽功能。分享给大家供大家参考,具体如下:

本文实例讲述了angularjs实现的简单拖拽功能。分享给大家供大家参考,具体如下:

<!doctype html>
<html ng-app="myapp">
  <head>
    <meta charset="utf-8">
    <title>www.jb51.net angularjs拖拽</title>
    <style>
    *{
      padding:0;
      margin:0;
    }
      .wei{
        width:100px;
        height:100px;
        background: red;
        position:absolute;
        cursor: pointer;
        /*left:0;top:0;*/
      }
    </style>
  </head>
  <body ng-controller="show">
      <div class="wei" wei-yi data="true"></div>
      <div class="wei" wei-yi data="false"></div>
    <script src="jquery.js" type="text/javascript" charset="utf-8"></script>
    <script src="angular.min.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript">
      var app = angular.module('myapp',[]);
      //自定义属性
      app.directive("weiyi",function(){
        return{
          restrict :'a',//a属性,e标签,c类名,d注释
          link :function(scope,element,attr){
            attr.data=angular.equals(attr.data,"true");
            //console.log(attr.data);
            console.log(element);
            element.on("mousedown",function(e){
              var that = $(this);
              console.log(attr.data);
              if(attr.data){
                $div=$("<div>");
                console.log($div);
                $div.css({"width":"100px","height":"100px","border": "2px dotted green","position":"absolute","left":that.offset().left,"top":that.offset().top});
                $div.appendto($("body"));
              }
              var x=e.clientx-$(this).offset().left;
              var y=e.clienty-$(this).offset().top;
              //console.log(x+":"+y);
              $(document).on("mousemove",function(e){
                if(attr.data){
                  $div.css({"left":e.clientx-x,"top":e.clienty-y});
                }else{
                  that.css({"left":e.clientx-x,"top":e.clienty-y});
                }
              });
              $(document).on("mouseup",function(e){
                //console.log($div);
                $(document).off();
                if(attr.data){
                  that.css({"left":$div.offset().left,"top":$div.offset().top});
                  $div.remove();
                }
              })
            })
          }
        }
      });
      app.controller('show',['$scope',function(scope$){
      }]);
    </script>
  </body>
</html>

运行效果如下:

AngularJS实现的简单拖拽功能示例

更多关于angularjs相关内容感兴趣的读者可查看本站专题:《angularjs指令操作技巧总结》、《angularjs入门与进阶教程》及《angularjs mvc架构总结

希望本文所述对大家angularjs程序设计有所帮助。