栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

Angular封装拖拽指令

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Angular封装拖拽指令

一:创建drag.directive.ts

代码如下:

    

import { Directive, ElementRef, Input,OnInit,Renderer,HostListener} from '@angular/core';


@Directive({ selector: '[myDrag]' })


//封装一个拖拽指令

export class HighlightDirective  implements onInit {

    constructor(private el: ElementRef,private rr:Renderer) {


    }


    //控制是否按下

    //设置为private,放置外部改变内部数据

    private isDown=false;

    private disX ;

    private disY ;

     

    ngonInit(){

    this.setColor(this.dragColor);

    }


   

   //点击事件

@HostListener('mousedown',['$event']) onMousedown(event) {

console.log(event);

this.isDown=true;

this.disX=event.clientX-this.el.nativeElement.offsetLeft;

this.disY=event.clientY-this.el.nativeElement.offsetTop;

}

//监听document移动事件事件

@HostListener('document:mousemove', ['$event']) onMousemove(event){

//判断该元素是否被点击了。

if(this.isDown){

  console.log("移动中");

  let newdisX=event.clientX;

  let newdisY=event.clientY;

  this.el.nativeElement.style.left=newdisX-this.disX+"px";

  this.el.nativeElement.style.top=newdisY-this.disY+"px";

  }

 

}

//监听document离开事件

@HostListener('document:mouseup',['$event']) onMouseup() {

//只用当元素移动过了,离开函数体才会触发。

if(this.isDown){

console.log("fail");

this.isDown=false;

}

}


private setColor(color){

this.el.nativeElement.style.background=color;

}


// 绑定到@Input属性

//绑定到@Input别名

//在指令内部,该属性叫dragColor,在外部,当我们绑定到它时,它叫myDrag。

    @Input('myDrag') dragColor: string;

}

二:在根模块引入指令

例如:

    

//注册指令--->用法类似于组件

import {HighlightDirective} from '../directive/drag.directive';

//列出程序中的组件

  declarations: [

    AppComponent,

    GeneralDetailComponent,

    HighlightDirective

  ],

三:使用


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/245785.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号