[英]Updated global variable not being passed to function inside a variable
所以我有這些:
var containerId = 'anim1'
var animation = bodymovin.loadAnimation({
container: document.getElementById(containerId),
renderer: 'svg',
loop: false,
autoplay: false,
path: "https://assets10.lottiefiles.com/packages/lf20_rd4wrn81.json"
});
function playanim() {
animation.goToAndPlay(0);
}
$('div').on('click', function() {
containerId = $(this).attr('id');
$('#text').text(containerId + ' was just clicked');
playanim();
})
全局變量containerId
在點擊事件上被更新,但是更新后的值沒有被傳遞給變量animation
中的相同containerId
。 不確定這是否是特定於 bodymovin 的問題 - 我怎樣才能讓它工作?
在以var animation =...
開頭的行中,您正在創建一個 object,將其container
屬性設置為document.getElementById(containerId)
(使用當時containerId
具有的任何值,即'anim1'
),然后將 object 傳遞給bodymovin.loadAnimation (大概是一個配置 - 我不熟悉那個庫)
單擊 div 時, containerId
的值正在更新,但這不會更改您之前創建的配置 object 中的container
屬性的值; 這仍然等於anim1
。 即使它確實發生了變化,除非 bodymovin 正在監視該配置 object,否則它可能沒有任何區別。 bodymovin.loadAnimation 很可能只是在初始化時檢查container
的值,然后再也不檢查它。
如果每次單擊 div 時重建 animation 可能會達到您想要的效果,例如像這樣(您可能也想在舊 div 中停止 animation?)
var animation // just declare it for now, assign below
// The following function will load the animation to the specified container
function setAnimation (containerId) {
console.log ("Loading animation into " + containerId)
animation = bodymovin.loadAnimation({
container: document.getElementById(containerId),
renderer: 'svg',
loop: false,
autoplay: false,
path: "https://assets10.lottiefiles.com/packages/lf20_rd4wrn81.json"
});
}
// Load it in 'anim1' first
setAnimation ('anim1')
function playanim() {
animation.goToAndPlay(0);
}
$('div').on('click', function() {
var id = $(this).attr('id')
console.log(id + ' was just clicked');
$('#text').text(id + ' was just clicked');
setAnimation (id); // re-initialize the animation
animation.addEventListener('data_ready',playanim);
})
在不了解 bodymovin 的更多信息(對不起)的情況下,我無法判斷這是否是一種非常低效的方法。 也許 bodymovin 有一種更輕量級的方法來更改已經加載的 animation 的容器,在這種情況下,您可以在單擊處理程序中執行此操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.