HTML5 customElements - 添加伪类

3
我正在开发一个自定义的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添加到我的新类中?
2个回答

1

1
据我所读,你无法在自定义元素的 CSS 中使用 :invalid 选择器。但是,你可以根据有效性设置 invalid 属性,然后使用 [invalid] 选择器。

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接