如何在Shepherd JS Tour中存储步骤常量并恢复attachTo默认配置?
关于Shepherd JS Tour的两个问题解答
1. 如何在常量中存储Tour步骤?
有两种常用实现方式:
- 初始化前预定义步骤常量:先把所有步骤配置存入常量,再传给Tour初始化参数,方便后续复用或修改原始配置:
// 定义步骤常量 const tourSteps = [ { id: 'step-1', text: '第一步引导内容', attachTo: { element: '#target-el-1', on: 'bottom' } }, { id: 'step-2', text: '第二步引导内容', attachTo: { element: '#target-el-2', on: 'right' } } ]; // 用常量初始化Tour const tour = new Shepherd.Tour({ steps: tourSteps });
- 从已初始化的Tour中提取步骤存为常量:如果Tour已经创建,可直接通过
tour.steps获取所有步骤并存储:
const currentTourSteps = tour.steps;
2. 动态修改并恢复Step的attachTo配置(解决attachToElement未定义问题)
你的代码报错主要源于语法错误、步骤获取时机不当、未提前存储原始配置三个问题,以下是修正后的实现方案:
核心思路
提前备份每个步骤的原始attachTo配置,避免修改后无法恢复;操作前先确认当前步骤存在;修正对象字面量的语法错误。
方案一:在步骤初始化时存储原始配置
// 定义步骤时,给每个步骤添加原始attachTo的备份 const tourSteps = [ { id: 'step-1', text: '引导文本', attachTo: { element: '#target-el', on: 'bottom' }, // 备份原始配置 originalAttachTo: { element: '#target-el', on: 'bottom' } } ]; const tour = new Shepherd.Tour({ steps: tourSteps }); // 动态修改/恢复的逻辑 const currentStep = tour.getCurrentStep(); // 先判断当前是否存在有效步骤,避免null报错 if (!currentStep) return; if (/* 你的触发条件 */) { // 修改为新的attachTo配置 currentStep.updateStepOptions({ attachTo: { element: currentStep.originalAttachTo.element, on: 'top' } }); } else { // 恢复原始配置 currentStep.updateStepOptions({ attachTo: { ...currentStep.originalAttachTo } }); }
方案二:单独用对象存储所有步骤的原始配置
如果不想修改步骤本身的结构,可以单独维护一个存储原始配置的对象:
const tourSteps = [ { id: 'step-1', text: '引导文本', attachTo: { element: '#target-el', on: 'bottom' } } ]; // 提前备份所有步骤的原始attachTo const originalAttachToMap = {}; tourSteps.forEach(step => { originalAttachToMap[step.id] = { ...step.attachTo }; }); const tour = new Shepherd.Tour({ steps: tourSteps }); // 动态修改逻辑 const currentStep = tour.getCurrentStep(); if (!currentStep) return; if (/* 你的触发条件 */) { currentStep.updateStepOptions({ attachTo: { element: originalAttachToMap[currentStep.id].element, on: 'top' } }); } else { currentStep.updateStepOptions({ attachTo: { ...originalAttachToMap[currentStep.id] } }); }
你的代码问题分析
- 语法错误:
{attachToElement.element, attachToElement.on}是无效的对象字面量,必须显式指定键名(element:和on:); - 时机问题:如果在Tour未启动(无当前步骤)时执行
tour.getCurrentStep(),会返回null,此时访问.attachTo会导致attachToElement未定义; - 存储逻辑问题:临时获取
tour.getCurrentStep().attachTo可能已经是修改后的配置,无法作为原始值恢复。
内容的提问来源于stack exchange,提问作者Ji Lin
相关产品推荐
相关产品推荐

