首页 > 解决方案 > A-frame 按钮 onClick 更改对象

问题描述

我正在尝试在 A-frame (aframe.io) 中创建一些东西,当按钮 onclick 事件发生时,立方体会改变颜色。这是我当前的代码:

 <script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script>
<button style="z-index: 999; position: fixed">RESIZE</button>
<script>
  AFRAME.registerComponent("foo", {
    init: function() {
      const btn = document.querySelector("button");
      const sphere = document.querySelector("a-sphere");
      btn.addEventListener("click", e => {
         sphere.setAttribute("color","red");
      })
    }
  })
</script>
<a-scene foo>
  <a-sphere position="0 1.25 -5" radius="1.25" color="#EF2D5E"></a-sphere>
</a-scene>

这里的代码运行良好,但它没有使用 onclick 事件。如何更改上面的代码,以便当按钮上有 onclick 功能并且该功能发生时颜色会发生变化?只是澄清一下,我知道上面的代码运行良好,但它使用事件侦听器来判断按钮何时被单击,我需要将其更改为 onclick 事件。

标签: javascripthtmlaframevirtual-realitywebvr

解决方案


定义一个变量s,然后,当 AFRAME 初始化时,分配一个函数来改变球体的颜色。将onclick事件附加到然后调用函数的按钮s

var s;
AFRAME.registerComponent("foo", {
  init: function() {
    const sphere = document.querySelector("a-sphere");
    s = function() {
      sphere.setAttribute("color", "red");
    }
  }
})
console.clear();//<-- this is to get rid of the console logs which clog up the snippet view
<script src="https://aframe.io/releases/1.2.0/aframe.min.js"></script>
<button style="z-index: 999; position: fixed" onclick="s()">RESIZE</button>
<script>
</script>
<a-scene foo>
  <a-sphere position="0 1.25 -5" radius="1.25" color="#EF2D5E"></a-sphere>
</a-scene>


推荐阅读