[Web Component] Allow External Styling of a Web Component's Shadow DOM

本文探讨了Shadow DOM如何保护组件免受样式冲突,并介绍了三种定义API的方法,允许用户在不破坏封装的情况下修改内联样式。通过示例代码展示了如何使用JavaScript改变封装样式,以及如何监听和响应属性变化。

The Shadow DOM protects your components from style conflicts. The same protection also makes it hard for users to modify the inner style for their own needs. In this lesson we go over 3 ways to define API for a controlled manipulation of encapsulated styles. 

 

<style>
    custom-element {
        --text-color: purple; // Define a variable for the color
    }
    div.text {
        color: red !important;
        text-decoration: underline;
        font-size: 36px;
    }
</style>

<template>
    <style>
        .text {
            color: var(--text-color, blue); // set 'blue' as default value
            text-decoration: overline;
            font-size: 28px;
        }
    </style>
    <div class="text">
        In the Shadow
    </div>
</template>

<script>
    const template = document.querySelector('template');
    class CustomElement extends HTMLElement {
        constructor() {
            super();
            this.attachShadow({mode: "open"});
            this.shadowRoot.appendChild(template.content.cloneNode(true));
        }

        // allow to use javascript to change the style
        changeStyles(styles) {
            const textElement = this.shadowRoot.querySelector('.text');
            Object.keys(styles).forEach(styleKey => {
                textElement.style[styleKey] = styles[styleKey];
            })
        }

        // listen for the attributes changes, here only listening 'color', 'text-decoration'
        static get observedAttributes() {
            return ['color', 'text-decoration'];
        }

       // Once the attribute changes, apply the style 
        attributeChangedCallback(attribute, oldValue, newValue) {
            this.changeStyles({[attribute]: newValue});
        }
    }
    window.customElements.define('custom-element', CustomElement);
</script>

<custom-element></custom-element>
<div class="text">Outside the shadow</div>

 

 

转载于:https://www.cnblogs.com/Answer1215/p/10998499.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值