![](/img/trans.png)
[英]How can I call a javascript function upon hovering an a-frame element, using its ID?
[英]Click and call javaScript function using A-Frame
我想使用aframe在javaScript中調用兩個函數。 這是我的代碼
AFRAME.registerComponent('house-hold', {
schema: {
type: 'selectorAll',
default: null
},
init: function () {
this.entities = [];
if ( this.data === null ) {
this.entities.push(this.el);
} else {
this.entities = this.data;
}
this.toggleHandler = this.toggleVisibility.bind(this);
},
play: function() {
this.el.addEventListener('click', this.toggleHandler);
},
pause: function() {
this.el.removeEventListener('click', this.toggleHandler);
},
hide: function(entities){
var entities = this.entities;
var cursor = this.el.sceneEl.querySelector('[cursor]');
for (var i = 0; i < entities.length; i++) {
entities[i].object3D.visible = false;
entities[i].pause();
entities[i].classList.remove('clickable');
entities[i].classList.add('clickable-disabled');
cursor.components.raycaster.refreshObjects();
}
},
show: function(entities){
var entities = this.entities;
var cursor = this.el.sceneEl.querySelector('[cursor]');
for (var i = 0; i < entities.length; i++) {
entities[i].object3D.visible = true;
entities[i].play();
entities[i].classList.remove('clickable-disabled');
entities[i].classList.add('clickable');
cursor.components.raycaster.refreshObjects();
}
},
toggleVisibility: function(e) {
var categoryScene = document.querySelectorAll('#category-scene');
var houseHoldCareScene = document.querySelectorAll('#house-hold-scene');
var personalCareScene = document.querySelectorAll('#personal-care-scene');
var toasterScene = document.querySelectorAll('#toaster-scene');
var cursor = this.el.sceneEl.querySelector('[cursor]');
show(houseHoldCareScene);
hide(categoryScene);
hide(personalCareScene);
hide(toasterScene);
}
});
這是我的代碼。 我稱之為隱藏和顯示功能。 但這沒有用。 單擊也沒有用。我認為我的調用方法不正確。 當我單擊它應該工作,但沒有。 如何正確調用這兩個功能? 如何解決這個問題呢?
我做了這樣的游標
<a-camera position="2 -2.5 12">
<!-- Only make entities with class="clickable" clickable. -->
<a-cursor raycaster="objects: .clickable"
fuse-timeout="2000"
material="color: #F4D03F; shader: flat"
opacity="0.9">
<!-- CLICK & FUSE ANIMATIONS -->
<a-animation begin="click" easing="ease-in" attribute="scale" dur="150" fill="forwards" from="0.1 0.1 0.1" to="1 1 1"></a-animation>
<a-animation begin="cursor-fusing" easing="ease-in" attribute="scale" dur="1500" fill="backwards" from="1 1 1" to="0.1 0.1 0.1"></a-animation>
</a-cursor>
</a-camera>
您必須使用this
指針調用函數,因為它們是組件的方法,而不是全局函數聲明:
this.show(houseHoldCareScene);
this.hide(categoryScene);
this.hide(personalCareScene);
首先,在組件中定義的調用函數需要具有this
關鍵字,因為它們封裝在組件中,而不是全局的(如D.Marcos在其anwser中所述)。
其次,如果您希望它可以立即工作,則需要在init
上創建事件監聽器:
init: function() {
// your current code (...)
this.toggleHandler = this.toggleVisibility.bind(this);
this.el.addEventListener('click', this.toggleHandler);
}
據我所知,進入/退出檢查器時會調用播放和暫停功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.