首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用DefinitelyTyped的Angular2上的Interact.js

使用DefinitelyTyped的Angular2上的Interact.js
EN

Stack Overflow用户
提问于 2016-06-06 18:42:56
回答 1查看 2.7K关注 0票数 4

我在项目中安装了interact.js angular2,但我不知道如何使用文档中描述的方法。

我的导入如下

代码语言:javascript
复制
import * as _ from 'interact';

在Angular2中是否存在全服务interact.js的可能性?如何创建对拖放的支持?

DT https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/interact.js

EN

回答 1

Stack Overflow用户

发布于 2018-02-13 00:16:37

我使用Renderer2来选择您想要处理的元素,您也可以原样传递类名,其余的用法与其他typescript类非常相似。让我们看一下interactjs的第一个示例,将这段html放入您的组件模板中

代码语言:javascript
复制
  <div id="drag-1" class="draggable">
    <p> You can drag one element </p>
  </div>
  <div id="drag-2" class="draggable">
    <p> with each pointer </p>
  </div>

在您的组件内部

代码语言:javascript
复制
import { Component, OnInit, Renderer2 } from '@angular/core';
import * as interact from 'interactjs';

@Component({
  selector: 'app-playground',
  templateUrl: './playground.component.html',
  styleUrls: ['./playground.component.css']
})
export class PlaygroundComponent implements OnInit {

  constructor(private renderer2: Renderer2) { }

  ngOnInit() {
    const draggableEl = this.renderer2.selectRootElement('.draggable');

    // target elements with the "draggable" class
    interact(draggableEl)
      .draggable({
        // enable inertial throwing
        inertia: true,
        // keep the element within the area of it's parent
        restrict: {
          restriction: 'parent',
          endOnly: true,
          elementRect: { top: 0, left: 0, bottom: 1, right: 1 }
        },
        // enable autoScroll
        autoScroll: true,

        // call this function on every dragmove event
        onmove: this.dragMoveListener,
        // call this function on every dragend event
        onend: function (event) {
          const textEl = event.target.querySelector('p');

          textEl && (textEl.textContent =
            'moved a distance of '
            + (Math.sqrt(Math.pow(event.pageX - event.x0, 2) +
              Math.pow(event.pageY - event.y0, 2) | 0))
              .toFixed(2) + 'px');
        }
      });
  }

  private dragMoveListener(event) {
    const target = event.target,
      // keep the dragged position in the data-x/data-y attributes
      x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx,
      y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;

    // translate the element
    target.style.webkitTransform =
      target.style.transform =
      'translate(' + x + 'px, ' + y + 'px)';

    // update the posiion attributes
    target.setAttribute('data-x', x);
    target.setAttribute('data-y', y);
  }

}

我不认为我们需要任何其他的服务层来使用它!

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37655352

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档