javascript - 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 事件。
解决方案
定义一个变量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>
推荐阅读
- ubuntu - rstudio 分段错误(核心转储)
- python - 在 Python 中,如何计算半径列表的周长?
- c - 指针 C 语言
- git - git pull --rebase origin HEAD 拉错分支。HEAD 代表什么?
- ios - 背景图像导致动画 popViewController 延迟/滞后
- java - 以特定方式合并大型 csv 文件
- python - sklearn.exceptions.NotFittedError:此 LabelEncoder 实例尚未安装
- rust - 如何从 Rust 中借用的泛型数组创建 HashSet?
- python - 如何在我的 django 项目中创建自定义模板标签
- ajax - 带有 CORS 和自定义标头的 AJAX 请求