Shopify站点model-viewer 3D动画如何添加暂停/播放切换按钮
Model-Viewer 3D动画暂停/播放切换功能修复方案
核心错误说明
- 事件绑定顺序错误:先绑定点击事件再动态插入按钮元素,导致绑定事件时目标元素不存在,事件完全不生效
- 逻辑判断语法错误:if判断条件同时判断
paused等于undefined且等于false,两个条件互斥永远无法成立,逻辑直接走反 - 属性读取方法错误:
paused是model-viewer的DOM属性,不是HTML标签属性,用attr()无法读取到正确的布尔值,应该直接访问原生DOM元素的属性 - 方法调用对象错误:
play()和pause()是原生model-viewer元素的内置方法,不能在jQuery封装对象上直接调用,需要转为原生DOM元素后调用 - 多处语法错误:函数声明缺少括号、未定义
selector和sound变量、末尾存在多余的闭合符号
修复后可运行代码
// 用事件委托绑定点击事件,支持动态插入的按钮 $(document).on('click', '.animation-pause', function() { // 获取当前按钮对应的原生model-viewer元素 const modelViewer = $(this).closest('model-viewer')[0]; if (!modelViewer) return; // 切换播放状态 if (modelViewer.paused) { modelViewer.play(); $(this).text('暂停'); } else { modelViewer.pause(); $(this).text('播放'); } }); // 给所有model-viewer插入控制按钮 $('model-viewer').each(function() { // 插入热点按钮,slot属性、data-position参数可根据实际需求调整 $(this).append('<button class="animation-pause" slot="hotspot-one" data-position="0 0 0" data-normal="0 1 0">暂停</button>'); }); // 若需要关联音频同步播放暂停,确保sound、对应model-viewer元素已正确定义,参考代码如下: // const sound = document.querySelector('#你的音频元素ID'); // const modelViewer = document.querySelector('model-viewer'); // const playRequest = document.querySelector("#overlay"); // if (sound && modelViewer) { // sound.addEventListener("pause", () => { // modelViewer.pause(); // }); // sound.addEventListener("play", () => { // modelViewer.play(); // playRequest?.classList.add("hide"); // }); // } // 热点按钮切换函数 function hotspotButton() { const modelViewer = document.querySelector('model-viewer'); if (!modelViewer) return; modelViewer.paused ? modelViewer.play() : modelViewer.pause(); }
内容的提问来源于stack exchange,提问作者Alexandre Buxo
相关产品推荐
相关产品推荐

