【问题标题】:Using CSS Variables on Stripe Elements在条纹元素上使用 CSS 变量
【发布时间】:2019-01-24 17:18:43
【问题描述】:

我正在使用Stripe Elements 进行信用卡结账。问题是,我不能(或者我根本不知道如何)在这个Stripe Element 上使用我自己的CSS variables。 当用户更改主题时,我需要使用CSS variables 来更改颜色。这是我当前的实现:

变量定义(我使用的是 SASS)

.theme1
    --color-1: red
    --color-2: pink
    // ...
.theme2
    --color-1: blue
    --color-2: lilec
    // ...
.theme3
    --color-1: orange
    --color-2: yellow
    // ...
// ...

CSS variables 是在一个类的范围内定义的,根据当前选择的主题,将其放入body

HTML(我使用的是 Angular 6)

<div #stripe></div>

打字稿

    @ViewChild('stripe') el: ElementRef;
    card: any;
    cardHandler = this.onChange.bind(this);
    async onSubmit() { /* ... */ }

    setupStripe(): void {
        this.card = stripeElements.create('card', {
            iconStyle: 'solid',
            style: {
                base: {
                    iconColor: 'var(--some-var)',
                    // using css variables here does not work
                    // ...
                },
            }
        });
        this.card.mount(this.el.nativeElement);
        this.card.addEventListener('change', this.cardHandler);
    }
    destroyStripe(): void {
        this.card.removeEventListener('change', this.cardHandler);
        this.card.destroy();
    }

    ngAfterViewInit() {
        this.setupStripe();
    }

    ngOnDestroy() {
        this.destroyStripe();
    }

    onChange({ error }) { /* ... */ }

样式(我正在使用 SASS)

.StripeElement
    background-color: var(--dy-bg-1)
    // I don't have access to font colors etc here
    color: var(--dy-txt-1) !important
    // !important also does not work

P.S.:对我来说重要的是,变量会在运行时发生变化(这就是我使用 CSS 变量的原因。

【问题讨论】:

    标签: html css angular sass stripe-payments


    【解决方案1】:

    Stripe 文档说

    Elements 为您创建由 Stripe 托管的 UI 组件

    即它们的输入字段位于不同的文档中,因此无法访问您的自定义 CSS 变量。

    “足够好”的解决方案可能是在 setupStripe 方法中读取 CSS 自定义属性值,并将这些值作为纯字符串传递:

    // Note: document.body is just an example:
    const styles = getComputedStyle(document.body);
    this.card = stripeElements.create("card", {
      iconStyle: "solid",
      style: {
        base: {
          iconColor: styles.getPropertyValue("--some-var")
          // ...etc
        }
      }
    });
    

    【讨论】:

    • 这非常适合一次性使用变量!不幸的是,更改主体样式后样式不会重新计算。 creating之后的cards样式可以改吗?
    • Stripe 文档说“可以使用 update() 动态更改元素的样式。此方法可用于模拟 CSS 媒体查询,在不同设备上查看时自动调整元素的大小。” .见stripe.com/docs/stripe-js/reference#other-methods
    • 谢谢,我不知道这个!我会试一试,如果有效,你会得到一个绿色箭头:)
    猜你喜欢
    • 2021-04-01
    • 2021-03-17
    • 2020-05-22
    • 1970-01-01
    • 2019-03-29
    • 2015-08-01
    • 1970-01-01
    • 2018-01-12
    • 2023-03-25
    相关资源
    最近更新 更多