如何在WooCommerce中调整PayPal按钮的位置?
解决支付按钮返回步骤后消失的问题

我尝试用JavaScript调整PayPal按钮的位置,但返回步骤1时按钮消失了,推测是元素被做了影子复制导致的。
原代码:
const section = document.getElementById('order_checkout_payment'); let contador = 0 const observer = new MutationObserver((mutationsList, observer) => { if (section.style.display === 'block') { if (contador == 0) { miFuncion(); contador += 1 } } }); observer.observe(section, { attributes: false, childList: true, subtree: true }); const wrapperPaypalButton = document.getElementById('ppc-button-ppcp-gateway').parentElement function miFuncion() { console.log(1) const paypaylInputOption = document.getElementById('payment_method_ppcp-gateway'); if (paypaylInputOption) { console.log(3) const padreSectionMetodoPago = paypaylInputOption.parentElement padreSectionMetodoPago.appendChild(wrapperPaypalButton) } // observer.disconnect(); }
问题分析
- 提前缓存的
wrapperPaypalButton引用会失效——返回步骤时页面可能重新渲染支付区域,旧DOM元素已被移除 contador限制只执行一次移动操作,返回后section重新显示也不会再触发调整- MutationObserver未监听
style属性变化,可能漏捕捉section显示状态的切换
修复后的代码
const section = document.getElementById('order_checkout_payment'); const observer = new MutationObserver((mutationsList, observer) => { // 用getComputedStyle获取实际显示状态,兼容CSS类控制的情况 if (window.getComputedStyle(section).display === 'block') { miFuncion(); } }); observer.observe(section, { attributes: true, attributeFilter: ['style'], // 只监听style属性变化,减少不必要的触发 childList: true, subtree: true }); function miFuncion() { // 每次执行都实时获取最新的DOM元素,避免引用失效 const paypalButton = document.getElementById('ppc-button-ppcp-gateway'); if (!paypalButton) return; const wrapperPaypalButton = paypalButton.parentElement; const paypaylInputOption = document.getElementById('payment_method_ppcp-gateway'); if (paypaylInputOption && wrapperPaypalButton.parentElement !== paypaylInputOption.parentElement) { paypaylInputOption.parentElement.appendChild(wrapperPaypalButton); } }
关键修改点
- 移除
contador限制,每次section显示时都检查并调整按钮位置 - 在
miFuncion内部实时获取按钮元素,确保拿到当前页面的最新节点 - 改用
window.getComputedStyle判断显示状态,兼容行内样式和CSS类控制的情况 - 配置Observer监听
style属性变化,确保能准确捕捉section的显示/隐藏切换 - 添加父元素判断,避免重复移动按钮造成不必要的DOM操作
内容的提问来源于stack exchange,提问作者JavierLoera
相关产品推荐
相关产品推荐

