You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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();
}

问题分析

  1. 提前缓存的wrapperPaypalButton引用会失效——返回步骤时页面可能重新渲染支付区域,旧DOM元素已被移除
  2. contador限制只执行一次移动操作,返回后section重新显示也不会再触发调整
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 11:40:21