【问题标题】:HTML5 customElements - adding pseudo-classesHTML5 customElements - 添加伪类
【发布时间】:2018-08-24 20:11:00
【问题描述】:

我正在开发一个自定义 HTML 类,它可以用作一种额外的表单类型,支持与 [name][value] 属性匹配的任何元素。

但是,当扩展一个类时,我发现我无法让伪选择 :invalid 工作。

class HTMLInlineInputElement extends HTMLElement{
    constructor(){
        super();
        this.addEventListener('input', function(event){
            this.value = this.innerHTML;
        })
    }
    connectedCallback(){}

    get name(){
        return this.getAttribute('name');
    }
    set name(value){
        return this.setAttribute('name', value);
    }
    get value(){
        return this.getAttribute('value');
    }
    set value(value){
        return this.setAttribute('value', value);
    }
    get valid(){
        return this.validity.valid;
    }
    set valid(value){
        return this.validity.valid = value;
    }
    checkValidity(){
        if( this.hasAttribute('required') &&  this.value == null || this.value.length == 0 ){
            console.log('req');
            this.valid = false;
        } else if( this.hasAttribute('pattern') && this.value.match( this.getAttribute('pattern') ) ){
            console.log('patt');
            this.valid = false;
        }
    }
}

if( typeof customElements !== 'undefined' ){
    customElements.define('inline-form', HTMLInlineFormElement);
    customElements.define('inline-input', HTMLInlineInputElement);
} else {
    document.createElement('inline-form', HTMLInlineFormElement);
    document.createElement('inline-input', HTMLInlineInputElement);
}

简而言之:我想将HTMLElement.invalid = true; 功能添加到我的类中,这样我就可以在CSS 中使用:invalid 选择器。如何将:is-selectors 添加到我的新班级?

【问题讨论】:

    标签: javascript css html custom-element createelement


    【解决方案1】:

    从我读过的所有内容来看,您不能在 CSS 中将 :invalid 选择器用于自定义元素。但是您可以根据有效性设置invalid 属性,然后改用[invalid] 选择器。

    尝试将您的代码更改为以下内容:

    get valid(){
      return !this.hasAttribute('invalid');
    }
    set valid(value){
      if (value) {
        this.removeAttribute('invalid');
      }
      else {
        this.setAttribute('invalid'), '');
      }
    }

    【讨论】:

      【解决方案2】:

      目前有一个提议添加到 Web 组件规范中,允许添加自定义伪元素。 You can track the discussion (any maybe help move it forward) on GitHub.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-09-26
        • 1970-01-01
        • 1970-01-01
        • 2012-03-15
        • 2018-06-13
        • 1970-01-01
        • 2022-06-28
        相关资源
        最近更新 更多