angular - 如何通过循环触发锚点列表的点击事件 - 在angular2中
问题描述
我正在尝试为 Angular 应用程序制作我们的团队滑块。我的场景是获取一个锚元素列表,并在触发点击之前稍微延迟地遍历它们(每次点击都会调用下一个滑块)。
接下来将显示我想要转换为 Angular 的 JS 代码 =>。
codepen上提供的源代码
注意:由于某种原因,前两张幻灯片是空的,没关系
HTML
<div id="slider">
<div id="0" class="SlideContainer">
.. empty
<a href="#1">Click Me 0</a>
</div>
<div id="1" class="SlideContainer">
.. empty
<a href="#2">Click Me 1</a>
</div>
<!-- angular ngFor starts from here => -->
<div id="2" class="SlideContainer">
<div class="img">
<img src="https://www.nicepng.com/png/detail/11-112605_punk-cat-berkley-cats-illustrations.png">
</div>
<a href="#3">Click Me 2</a>
</div>
......... etc
</div>
CSS
#slider {
border: solid 1px #000;
height: 500px;
padding: .5%;
margin: 0;
overflow: hidden;
white-space: nowrap;
scroll-behavior: smooth;
}
.SlideContainer{
vertical-align: top;
border: solid 1px #000;
height: 99% ;
width: 33%;
margin: .5% 0;
display: inline-block;
}
.SlideContainer a{
display: none;
}
.img {
overflow: hidden;
max-width:200px;
max-height:200px;
border-radius: 50%;
display: block;
margin: 10px auto 0 auto;
text-align: center;
}
.img img{
height: 200px;
width: 200px;
}
JS
var i = 3;
var listA = document.getElementsByTagName("a");
var timer;
function SlideLoop() {
timer = setTimeout(() => {
listA[i].click();
if (i < 12)
{i++}
else
{i = 1}
SlideLoop();
}, 2000);
};
SlideLoop();
现在我只需要在 Angular TS 中应用相同的 JS 场景。这是我在 Angular 中的尝试
TS
constructor(
private slidesHref: ElementRef,
@Inject(DOCUMENT) private _document: HTMLDocument
) {}
// attempt 1
elements = this.slidesHref.nativeElement.querySelectorAll('.SlideContainer a');
// attempt 2
elem = this._document.querySelectorAll('.SlideContainer a');
ngOnInit(){
this.elements[4].click();
this.elems.forEach(e => e.dispatchEvent(new Event('click')));
}
再说一遍:我需要获取锚点列表并使用循环和触发单击来遍历它们,如 JS 代码示例中所示,但使用 Angular(TS)。
解决方案
推荐阅读
- d3.js - 向使用 c3js 制作的条形图添加图标
- python - 如何扩展 CoreNLP + Flask?
- java - Jenkins 无法从本地存储库中找到 maven 依赖项
- python - 在python数据框中创建具有多个名称的列
- angular - 如何根据 Angular mat-options 中的某些条件在下拉列表中列出选项?
- java - 为每个项目添加 Onclick 适配器以打开新的不同活动
- sql - 使用 charindex 优化子字符串查询以修剪字符串的左侧部分
- angular - 在 Angular 中与单击其他元素冲突的元素上的焦点
- c++ - lower_bound lambda 比较错误
- python - 为什么 Pycharm 不能运行具有相对导入的代码?