【发布时间】:2018-07-20 11:45:33
【问题描述】:
以编程方式将片段添加到Reveal.js 中的幻灯片的正确方法是什么?我在幻灯片上有一个 JavaScript 小部件,它可以通过 5 种状态,我想通过片段转换来通过它们。
我尝试使用 虚拟片段 实现类似的效果,如下面的代表性示例所示。这是为了在片段更改时更改图像的src。不过,这个例子有一个问题。通过多次按previous 接近幻灯片时,幻灯片应从其最后一个片段状态开始。然而,在示例中,图像 src 从状态 1 开始,并且不知道如何进一步返回其他 previous 步骤。
任何指针将不胜感激!
<img src="img1.png" id="my-image">
<span class="fragment update-img-src" data-target="my-image" data-src="img2.svg"></span>
<script>
Reveal.addEventListener('fragmentshown', function(event) {
if (event.fragment.classList.contains('update-img-src')) {
// Find the target image by ID
var target = document.getElementById(event.fragment.dataset.target);
// Keep a stack of previously shown images, so we can always revert back on 'fragmenthidden'
if (target.dataset.stack == null) {
target.dataset.stack = JSON.stringify([target.getAttribute('src')]);
}
target.dataset.stack = JSON.stringify([event.fragment.dataset.src, ...JSON.parse(target.dataset.stack)]);
// Update the image
target.setAttribute('src', event.fragment.dataset.src);
}
});
Reveal.addEventListener('fragmenthidden', function(event) {
if (event.fragment.classList.contains('update-img-src')) {
// Return to the previously shown image.
// Remove the top from the history stack
var target = document.getElementById(event.fragment.dataset.target);
if (target.dataset.stack == null) {
console.log('Trying to hide', event.fragment.dataset.src, 'but there is no stack.');
} else {
var [_, ...tail] = JSON.parse(target.dataset.stack);
target.dataset.stack = JSON.stringify(tail);
// Set the image source to the previous value
target.setAttribute('src', tail[0]);
}
}
});
</script>
【问题讨论】:
-
我怀疑这会很棘手。我查看了revealjs代码,它似乎只从DOM中获取它的状态。
标签: javascript reveal.js