css variable usage (native js, applet)

Background: To write a dynamic effect, you need to request the interface to get the data first, and then calculate the height according to the data. At this time, you think of scss and less variable writing, but since the project is css, can the wechat applet css also be like scss/ Like less, does it support variable writing?

The answer is definitely yes.

Summarize the use of variables in the small program css:

1. The original definition method of css

First of all, css variables are supported in native html and css. Define the required variables in the root node, and then they can be used on the entire page. It is agreed that the variable starts with --, and the var() function is used when calling.

The usage is as follows:

<style>
    :root {
        --final-top: 40px;
    }

    .my-wapper{
        top: var(--final-top);
    }
</style>

In the WeChat applet, the principle is the same, the difference is that the root node of the applet is the page selector.

Define and use in the wxss file: (It can also be defined in app.wxss for global use)

pege {
    --final-top: 40px;
}

.my-wapper {
    top: var(--final-top);
}

Also available in wxml:

<view style="top: (--final-top);">
    可以直接在wxml里面使用wxss变量!
</view>

2. Define in js

Native js supports dynamic modification of css, can small programs do it?

Because I need to get the data returned by the interface before processing, the above method will not work, then we can directly define it in the js file, we need to use setData, and then we can use it in the wxss file. For example:

 this.setData({
     style: `--point-final-height: ${130 * (19 - randomScore)}rpx;`
 })
.point-box {
    width: 328rpx;
    height: 131rpx;
    background: rgba(255, 254, 238, 0);
    position: absolute;
    top: 0;
    animation: bounce_box 1.5s linear 1s forwards;
}

@keyframes bounce_box {
    0% {
        top: 0rpx;
    }

    100% {
        top: var(--point-final-height);
    }
}

おすすめ

転載: blog.csdn.net/animatecat/article/details/128327353