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

如何动态设置CSS伪元素属性,实现视频水印位置自定义?

动态修改伪元素属性实现水印位置自定义方案

核心思路:通过CSS自定义属性(CSS变量)实现伪元素样式动态控制,仅需1个CSS类即可满足所有位置切换需求,完全消除重复代码。

步骤1:修改CSS代码,仅保留单个wrapper类

/*Video.module.css*/
.wrapper {
    position: relative;
    height: 100%;
    /* 定义四个位置偏移CSS变量,默认值为左上角配置 */
    --watermark-top: 2%;
    --watermark-right: initial;
    --watermark-bottom: initial;
    --watermark-left: 2%;
}

.wrapper::before {
    display: block;
    position: absolute;
    /* 直接引用CSS变量作为位置属性值 */
    top: var(--watermark-top);
    right: var(--watermark-right);
    bottom: var(--watermark-bottom);
    left: var(--watermark-left);
    height: 18%;
    width: 18%;
    content: '';
    background: red;
}

步骤2:修改JSX代码,动态设置CSS变量

import styles from 'styles/Video.module.css';
import React, {useState, useMemo} from 'react';

const Video = ({ src }) => {
    //可选值:'top-left', 'bottom-left', 'top-right', 'bottom-right'
    const [position, setPosition] = useState('top-left'); 

    // 根据选中的位置动态生成CSS变量配置
    const watermarkStyle = useMemo(() => {
        const baseConfig = {
            '--watermark-top': 'initial',
            '--watermark-right': 'initial',
            '--watermark-bottom': 'initial',
            '--watermark-left': 'initial',
        }
        switch(position) {
            case 'top-left':
                return {
                    ...baseConfig,
                    '--watermark-top': '2%',
                    '--watermark-left': '2%'
                }
            case 'top-right':
                return {
                    ...baseConfig,
                    '--watermark-top': '2%',
                    '--watermark-right': '2%'
                }
            case 'bottom-left':
                return {
                    ...baseConfig,
                    '--watermark-bottom': '2%',
                    '--watermark-left': '2%'
                }
            case 'bottom-right':
                return {
                    ...baseConfig,
                    '--watermark-bottom': '2%',
                    '--watermark-right': '2%'
                }
            default:
                return baseConfig
        }
    }, [position])

    return (
        <div className={styles.wrapper} style={watermarkStyle}>
            <video src={src}>
                <track type='captions' />
            </video>
            {/* 位置切换按钮相关代码 */}
        </div>
    );
};

方案优势

  • 无重复CSS代码,所有位置配置逻辑收敛到JS侧的映射关系中,后续新增位置仅需新增switch分支即可,无需修改CSS
  • 扩展性强,后续如果需要支持用户自定义偏移量、水印大小、透明度等,仅需新增对应的CSS变量,在JS侧动态传值即可,无需调整代码结构

内容的提问来源于stack exchange,提问作者gcksean

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 13:06:04