在A-Frame中动态添加实体后颜色更改停止工作的解决方法是使用setComponent方法来更改颜色属性,并在实体添加后手动调用它。这是示例代码:
AFRAME.registerComponent('color-changer', {
init: function() {
var el = this.el;
var baseColor = '#ff0000';
el.addEventListener('click', function() {
el.setAttribute('color', baseColor);
});
}
});
function addEntity() {
var scene = document.querySelector('a-scene');
var newEntity = document.createElement('a-box');
newEntity.setAttribute('color', '#00ff00');
newEntity.setAttribute('position', '0 2 -5');
newEntity.setAttribute('color-changer', '');
scene.appendChild(newEntity);
// 更新颜色属性
newEntity.setAttribute('material', 'color', '#00ff00');
}