Angular根据另一个HTML元素的位置设置ngStyle的margin
创始人
2024-10-25 02:31:00
0

要根据另一个HTML元素的位置设置ngStyle的margin,可以使用Angular的ViewChild和ElementRef来获取对应元素的位置信息,然后根据这些信息来设置ngStyle的margin。

下面是一个示例代码:

在 HTML 文件中:

Element 1
Element 2

在 TypeScript 文件中:

import { Component, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
})
export class ExampleComponent {
  @ViewChild('element1', {static: true}) element1: ElementRef;
  @ViewChild('element2', {static: true}) element2: ElementRef;

  setMargin(element1: ElementRef, element2: ElementRef): any {
    const rect1 = element1.nativeElement.getBoundingClientRect();
    const rect2 = element2.nativeElement.getBoundingClientRect();

    const marginTop = rect2.top - rect1.top;
    const marginLeft = rect2.left - rect1.left;

    return {
      'margin-top': `${marginTop}px`,
      'margin-left': `${marginLeft}px`
    };
  }
}

在上述代码中,我们使用ViewChild来获取对应的HTML元素的引用,然后使用ElementRef的nativeElement属性来获取元素的位置信息(通过getBoundingClientRect方法)。最后,我们根据这些位置信息计算出margin的值,并返回一个包含margin样式的对象,通过ngStyle绑定到element2上。

相关内容

热门资讯

透视智能ai!hhpoker辅... 透视智能ai!hhpoker辅助挂是真的吗(透视)新蜜瓜大厅破解(一直真的是有辅助辅助器)-哔哩哔哩...
透视总结!约局吧作必弊脚本(透... 透视总结!约局吧作必弊脚本(透视)红龙poker有辅助吗(辅助)确实真的是有脚本(哔哩哔哩)一、约局...
据监测!aa poker辅助(... 据监测!aa poker辅助(透视)楚天游卡五星辅助器(确实存在有辅助工具)-哔哩哔哩1、每一步都需...
透视学习!智星德州可以透视吗(... 透视学习!智星德州可以透视吗(透视)xpoker辅助控制(辅助)真是一直都是有攻略(哔哩哔哩)1)智...
随着!aa poker辅助包(... 随着!aa poker辅助包(透视)科乐游戏辅助脚本视频(都是真的有辅助工具)-哔哩哔哩1、首先打开...
透视总结!werplan免费挂... 透视总结!werplan免费挂下载(透视)poker world辅助器(辅助)真是一直总是有app(...
今年以来!wepoker免费脚... 今年以来!wepoker免费脚本咨询(透视)途游辅助软件网站(原来是真的辅助插件)-哔哩哔哩1、首先...
透视步骤!德州来玩辅助器(透视... 透视步骤!德州来玩辅助器(透视)pokemmo脚本辅助器(辅助)竟然真的是有软件(哔哩哔哩)1、该软...
最新消息!wepoker挂(透... 最新消息!wepoker挂(透视)新畅游互娱辅助(真是有辅助平台)-哔哩哔哩1、任何新畅游互娱辅助透...
透视窍门!来玩app破解(透视... 透视窍门!来玩app破解(透视)竞技联盟辅助(辅助)原来一直都是有app(哔哩哔哩)1、竞技联盟辅助...