本文详解如何通过原生 javascript 实现点击不同按钮时,将指定表单(如 `#answer-form`)动态插入到对应目标位置(如注释标记 `` 所在的父容器),同时支持展开/收起切换逻辑。
在实际开发中,常需实现“一个表单复用、按需定位”的交互效果——例如评论区中多个回复按钮共用同一个回复表单,点击任一按钮时,表单应自动移动至该按钮所在评论区块的指定插入点(如 后的位置),并显示;再次点击则隐藏;切换按钮时自动解绑并重新挂载。以下是专业、健壮的实现方案:
لطفا پاسخ خود را بنویسید
... پاسخ 8
document.addEventListener('DOMContentLoaded', () => {
const answerForm = document.getElementById('answer-form');
const answerButtons = document.querySelectorAll('.answer-btn');
answerButtons.forEach(btn => {
btn.addEventListener('click', function () {
const commentSection = this.closest('.comment-section');
const targetContainer = commentSection?.querySelector('.move-here');
// 若表单当前已显示且位于当前区块 → 隐藏
if (answerForm.style.display === 'block' &&
answerForm.parentElement === targetContainer) {
answerForm.style.display = 'none';
return;
}
// 否则:先从原位置移除(安全操作),
再插入新位置并显示
if (answerForm.parentElement) {
answerForm.parentElement.removeChild(answerForm);
}
if (targetContainer) {
targetContainer.appendChild(answerForm);
answerForm.style.display = 'block';
} else {
console.warn('⚠️ 未找到 .move-here 插入点,请检查 HTML 结构');
}
});
});
});该方案兼顾兼容性(支持 IE9+)、可读性与扩展性,适用于各类动态表单复用场景。