表单答案显示位置异常原因及调整至选中选项下方的实现方法
问题解答:交互式表单答案位置调整
问题1:为什么答案会显示在所有问题下方?
这是因为你把承载答案的<div id="q4">和<div id="q5">放在了所有问题DOM元素的末尾,而且当前代码只是通过给这些div添加active类,让它们从默认的display:none状态变成显示状态。它们在DOM结构里的位置就决定了显示时会出现在页面最后。
问题2:如何让答案显示在被选中的选项下方?
我们可以调整代码逻辑,不再预先放置答案div,而是在触发终端问题时动态生成答案元素,并插入到选中选项的附近。具体修改步骤如下:
1. 更新问题数据结构,补充终端问题的答案文本
首先给每个终端问题添加对应的答案内容,这样我们可以直接从数据里获取答案,不用依赖预先写好的DOM:
let questions = [ { id: "q1", terminal: false, yes: "q2", no: "q5" }, { id: "q2", terminal: false, yes: "q3", no: "q5" }, { id: "q3", terminal: false, yes: "q4", no: "q4", bo: "q4" }, { id: "q4", terminal: true, text: "answer 1" }, // 新增答案文本 { id: "q5", terminal: true, text: "answer 2" } // 新增答案文本 ];
2. 修改点击处理函数,动态插入答案
调整processResponse函数,当检测到选中的选项指向终端问题时,创建答案元素并插入到选中选项的下方,同时处理重复答案的问题:
document.addEventListener("click", processResponse); function processResponse(event) { if (event.target.classList.contains("box")) { const box = event.target; const question = box.parentElement; const response = box.dataset.response; const boxAndSibling = question.querySelectorAll(".box"); const sibling = response == "no" ? boxAndSibling[0] : boxAndSibling[1]; if (!sibling.classList.contains("check-box")) { box.classList.toggle("check-box"); // 先移除当前问题里已有的答案,避免重复显示 const existingAnswer = question.querySelector(".answer"); if (existingAnswer) { existingAnswer.remove(); } for (let quest of questions) { if (quest.id == question.id) { const nextQuestId = quest[response]; const nextQuestData = questions.find(q => q.id === nextQuestId); if (nextQuestData.terminal) { // 动态创建答案元素 const answerEl = document.createElement("div"); answerEl.className = "answer"; answerEl.textContent = nextQuestData.text; // 插入到选中选项的后面 box.insertAdjacentElement("afterend", answerEl); } else { // 非终端问题,正常显示下一个问题 const nextQuest = document.getElementById(nextQuestId); nextQuest.classList.toggle("active"); } } } } } }
3. 简化HTML结构,移除预先放置的答案div
把原来页面末尾的<div id="q4">和<div id="q5">删掉,因为现在答案是动态生成的:
<div id="q1"> Question number 1<br /> <span class="box" data-response="yes">Yes</span> <span class="box" data-response="no">No</span><br /> </div> <div id="q2" class="nested"> <span>Question number 2</span><br /> <span class="box" data-response="yes">Yes</span> <span class="box" data-response="no">No</span><br /> </div> <div id="q3" class="nested"> <span>Read:</span><br /> <span class="box" data-response="yes">read and click 1</span><br /> <span class="box" data-response="no">read and click 2</span><br /> <span class="box" data-response="bo">read and click 3</span><br /> </div>
4. (可选)给答案添加样式
可以加一点CSS让答案更突出:
.answer { margin-top: 8px; font-size: 1.2em; color: #2c3e50; font-weight: bold; }
这样修改后,当你选中某个指向终端问题的选项时,答案就会直接显示在该选项的下方啦~
内容的提问来源于stack exchange,提问作者arcadyia
相关产品推荐
相关产品推荐

