简体   繁体   English

我可以为动态创建的two.js元素添加类吗?

[英]Can I add class to dynamically created two.js element?

I am using the code showed below to create 46 small circles within a wrapper (div) draw-shapes; 我使用下面显示的代码在包装器(div)绘制形状中创建46个小圆圈;

let elem = document.getElementById('draw-shapes');
let params = { width: 1024, height: 768 };
let two = new Two(params).appendTo(elem);

for (let i = 1; i < 47; i++) {
  circle = two.makeCircle(x, y, radius);
  circle.fill = 'green';
  circle.stroke = 'white';
  circle.linewidth = 1;
  circle.id = i;
}

All drawings are made with the Two.js library. 所有图纸都是使用Two.js库制作的。 I read in the documentation I can change the id of the created element, but I also need to assign a class to each element. 我在文档中读到我可以更改已创建元素的id,但我还需要为每个元素分配一个类。 I have tried everything from pure js setAttribute to jQuery .attr and .addClass methods, but none of them worked, so I started to wonder if this is even possible to do? 我已经尝试了从纯js setAttribute到jQuery .attr和.addClass方法的所有方法,但它们都没有工作,所以我开始怀疑这是否可能做到了? If someone knows a way, please let me know how. 如果有人知道某种方式,请告诉我如何。 Thank. 谢谢。

There is not internal utility or property to get to the DOM node of each Two element. 没有内部实用程序或属性可以访问每个Two元素的DOM节点。

But the id you specify is indeed added as two-<specified-id> to the actual node. 但是您指定的id确实被添加为实际节点的two-<specified-id>

So you can use the normal document.getElementById . 所以你可以使用普通的document.getElementById

So in your case 所以在你的情况下

 let elem = document.getElementById('draw-shapes'); let params = { width: 300, height: 300 }; let two = new Two(params).appendTo(elem); for (let i = 1; i < 20; i++) { const circle = two.makeCircle(i * 10, i * 10, 40); circle.fill = 'green'; circle.stroke = 'white'; circle.linewidth = 1; circle.id = `two-circle-${i}`; } two.update(); // add classname to every fifth element; for (let i = 1; i < 20; i += 5) { const circleNode = document.getElementById(`two-circle-${i}`); circleNode.classList.add('classname'); circleNode.addEventListener('mouseover', function() { const path = two.scene.getById(this.id) path.scale = 1.2; two.update(); }); circleNode.addEventListener('mouseout', function() { const path = two.scene.getById(this.id) path.scale = 1; two.update(); }); } 
 .classname { stroke-width: 5; stroke: red; fill:yellow; cursor:pointer; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/two.js/0.6.0/two.js"></script> <div id="draw-shapes"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM