gpt4 book ai didi

angular - 获取点击的div的宽度、高度和偏移量——Angular 2

转载 作者:太空狗 更新时间:2023-10-29 18:16:17 29 4
gpt4 key购买 nike

我有一个模板,它使用 *ngFor 和一个单独的 div 元素创建链接列表,我想根据当前事件的链接更改其位置。

模板:

<div #divHandle
*ngFor="let link of links; let i = index"
class="div-link"
(click)="changeActiveLink(i)">
<h2>{{link}}</h2>
</div>
<div
[@indexState]="activeLink"
id="highlighter"></div>

这导致结构如下:

<div class="div-link">
<div (click)="changeActiveLink(0)"><h2>Link 1</h2></div>
<div (click)="changeActiveLink(1)"><h2>Link 2</h2></div>
<div (click)="changeActiveLink(2)"><h2>Longer link 1</h2></div>
<div (click)="changeActiveLink(3)"><h2>Longer link 2</h2></div>
</div>
<div id="highlighter"></div>

我希望我的荧光笔 div 在 activeLink = 0 时获得 Link 1 的宽度。类似于这个普通的 js:

var High = document.getElementById('highlighter');
High.style.width = document.getElementsByClass('div-link')[0].children[activeLink].offsetWidth; //activeLink = 0

在我的 app.component.ts 文件中:

import { Component, AfterViewInit, ViewChildren, Directive, QueryList, ElementRef} from '@angular/core';

@Directive({selector: '[class~=div-link]'})
@Directive({selector: '.div-link'}) // variant
@Directive({selector: '#divHandle'}) // variant
@Directive({selector: '[divHandle]'}) // variant
export class ChildDirective {
constructor(elem: ElementRef){}
}

@Component({
selector: 'my-app',
...
})
export class AppComponent implements AfterViewInit {
@ViewChildren(ChildDirective) childrenContent: QueryList<ChildDirective>;

ngAfterViewInit(){
console.log(this.childrenContent);
}
}

当我记录 childrenContent 时,我得到一个 QueryList 对象,但它是空的,没有可从中获取信息的元素。

我已经尝试了几个 @Directive 选择器,但我的 QueryList 总是空的。

最佳答案

您可以使用 $event 属性来处理宽度、高度、偏移量等。通过使用这种方法,传统的 javascript 开始发挥作用,如下所示

HTML代码如下

<div *ngFor="let link of links;" class="div-link" 
height="100px"
width="30px"
(click)="changeActiveLink($event)">
<h2>{{link}}</h2>
</div>
<div height="height" width="width" id="highlighter">some text</div>

将来自上方 div 元素的点击元素处理为

changeActiveLink(value){
this.height=value.srcElement.parentElement.attributes['height'].value;
this.width=value.srcElement.parentElement.attributes['width'].value;
console.log(this.width);
console.log(this.height);
}

注意:在上面的示例中,点击事件发生在 letter 上,因此我们将获取 srcElement 作为 h2,所以我使用的是 parentElement。在实时情况下,您可以通过在方法中包含 if 条件的任何一种方式来处理它。

您还可以 console.log 被点击的元素并获得更多想法来实现这一目标。

LIVE DEMO

关于angular - 获取点击的div的宽度、高度和偏移量——Angular 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42542782/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com