html - 以百分比计算 getBoundingClientRect

标签 html css angular getboundingclientrect

我已经在使用 getBoundingClientRect() 将子元素 wrt 的 getBoundingClientRect() 计算为 px 中的父元素并从一个组件传递到另一个组件,并且能够将子元素放置在预期位置,但是我想制作子元素响应父元素,为此我需要 % 中的顶部和左侧位置 我已经尝试从控制台将值和单位从 px 更改为 % 并且能够获得所需的响应速度,但是尝试在代码中以百分比计算并没有按预期工作,它没有将子元素放在正确的位置,尽管响应速度实现了。

  minX: viewRect.left - movableClientRect.left + movable.position.x,
  maxX: viewRect.right - movableClientRect.right + movable.position.x,
  minY: viewRect.top - movableClientRect.top + movable.position.y,
  maxY: viewRect.bottom - movableClientRect.bottom + movable.position.y

 this.dataService.setData(this.zonePosition = 
 {
  x : (viewRect.left - movableClientRect.left)/viewRect.left ,
  y: (viewRect.top - movableClientRect.top)/viewRect.top
  }

在较早的代码中,我只执行 viewRect.left - movableClientRect.left ,因此值以像素为单位,现在我尝试除以 viewRect.left 然后 * 100 将其转换为 % 但百分比值没有正确放置子元素。

更新计算位置的指令

可移动指令 在此我计算子元素的 x 和 y pos

interface Position {
  x: number;
  y: number;
}

@Directive({
 selector: '[appMovable]'
})
export class MovableDirective extends DraggableDirective {
@HostBinding('style.transform') get transform(): SafeStyle {
   return this.sanitizer.bypassSecurityTrustStyle(
  `translateX(${this.position.x}%) translateY(${this.position.y}%)`
  );
 }

 @HostBinding('class.movable') movable = true;

 position: Position = {x: 0, y: 0};
 zonePosition = {x:0, y:0, id:""}

 private startPosition: Position;

 @Input('appMovableReset') reset = false;

 constructor(private sanitizer: DomSanitizer, public element: ElementRef, 
  private dataService: DataService) {
  super(element);
  }

 @HostListener('dragStart', ['$event'])
  onDragStart(event: PointerEvent) {
   this.startPosition = {
     x: event.clientX - this.position.x,
     y: event.clientY - this.position.y
   }
 }

 @HostListener('dragMove', ['$event'])
  onDragMove(event: PointerEvent) {
   this.position.x = event.clientX - this.startPosition.x;
   this.position.y = event.clientY - this.startPosition.y;
  }

  @HostListener('dragEnd', ['$event'])
   onDragEnd(event: PointerEvent) {
    if (this.reset) {
     this.position = {x: 0, y: 0};
    }
   }
   }

我在其中计算子元素的左侧和顶部并将其分配给数据服务的指令

  Directive({
   selector: '[appMovableArea]'
  })
  export class MovableAreaDirective implements AfterContentInit {
  @ContentChildren(MovableDirective) movables: QueryList<MovableDirective>;

  private boundaries: Boundaries;
  private subscriptions: Subscription[] = [];

  zonePosition = {x:0, y:0, id:""}

  constructor(private element: ElementRef, private dataService: DataService) 
  {}

  ngAfterContentInit(): void {
   this.movables.changes.subscribe(() => {
   this.subscriptions.forEach(s => s.unsubscribe());

   this.movables.forEach(movable => {
   this.subscriptions.push(movable.dragStart.subscribe(() => 
       this.measureBoundaries(movable)));
   this.subscriptions.push(movable.dragMove.subscribe(() => 
   this.maintainBoundaries(movable)));
   });
   });

   this.movables.notifyOnChanges();
    }

   private measureBoundaries(movable: MovableDirective) {
    const viewRect: ClientRect = 
       this.element.nativeElement.getBoundingClientRect();
    const movableClientRect: ClientRect = 
       movable.element.nativeElement.getBoundingClientRect();

    this.dataService.setData(this.zonePosition= {x : (viewRect.left - 
      movableClientRect.left)/viewRect.left , y: (viewRect.top - 
      movableClientRect.top)/viewRect.top, id: "" })

    this.boundaries = {
      minX: viewRect.left - movableClientRect.left + movable.position.x,
      maxX: viewRect.right - movableClientRect.right + movable.position.x,
      minY: viewRect.top - movableClientRect.top + movable.position.y,
      maxY: viewRect.bottom - movableClientRect.bottom + movable.position.y
    };
   }

    private maintainBoundaries(movable: MovableDirective) {
     movable.position.x = Math.max(this.boundaries.minX, 
      movable.position.x);
    movable.position.x = Math.min(this.boundaries.maxX, movable.position.x);
    movable.position.y = Math.max(this.boundaries.minY, movable.position.y);
    movable.position.y = Math.min(this.boundaries.maxY, movable.position.y);
   }
   }

最佳答案

如果您已经有了相对于容器元素的位置(以像素为单位),那么您只需将这个以像素为单位的值除以容器的大小(以像素为单位),然后乘以 100:

perc_x = px_x / px_width * 100;
perc_y = px_y / px_height * 100;

elem = document.querySelector('.content');
container = document.querySelector('.container');
const mouse = {
  x: null,
  y: null,
  down: false
};
let will_draw = false;

elem.onmousedown = e => {
  mouse.down = true;
};
onmouseup = e => {
  mouse.down = false;
};
document.onmousemove = e => {
  if(!mouse.down) { return; }

  const container_rect = container.getBoundingClientRect();
  // relative to container, in px
  mouse.x = e.clientX - container_rect.left;
  mouse.y = e.clientY - container_rect.top;
  if(!will_draw) {
    requestAnimationFrame(draw);
    will_draw = true;
  }
}

function draw() {
  will_draw = false;
  const { width, height} = container.getBoundingClientRect();
  const perc_x = mouse.x / width * 100;
  const perc_y = mouse.y / height * 100;
  // -5 to center (elem has its width set to 10%)
  elem.style.setProperty('left', (perc_x - 5) + '%');
  // -5 to center (elem has its height set to 10%)
  elem.style.setProperty('top', (perc_y - 5) + '%');
}
.container {
  width: 80vw;
  height: 80vh;
  border: 1px solid;
  position: relative;
}
.content {
  width: 10%;
  height: 10%;
  position: absolute;
  top: 45%;
  left: 45%;
  background: green;
}
<div class="container">
  <div class="content">
  </div>
</div>

关于html - 以百分比计算 getBoundingClientRect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57497793/

相关文章:

css - 垂直位置的 react-responsive-carousel control-dots

html - 我如何平均间隔 css 网格列?

javascript - 在规范文件中,如何测试以事件作为参数的组件方法?

jquery - 选项卡 DIV 停靠在浏览器中。单击时使用 jquery 滑入和滑出屏幕

javascript - 为什么 jQuery 不能在 IE11 中运行

javascript - 无法使用 Bootstrap 和 Node 获取 POST 数据

html - :hover does not change my anchor's list properties

Jquery-UI 自动完成自定义数据 - 图像不会在自动完成的下拉列表中呈现

angular - 在 Angular 上运行 karma 测试时为 "Uncaught [object Object]"

angular - 如何在 Angular (v6) 中导入