Skip to content
目录

radio

单项选择器。用于替代原生input[type=radio]

使用方式

html
<!-- 引入 -->
<script type="module">
    import '../components/radio/index.js';
</script>
<!-- 使用 -->
<xy-radio>radio</xy-radio>

禁用disabled

通过disabled可以禁用开关。

radio禁用
html
<xy-radio disabled>radio</xy-radio>

JavaScript操作getset

js
radio.disabled;//获取
radio.disabled = false;
radio.disabled = true;
//原生属性操作
radio.setAttribute('disabled','');
radio.removeAttribute('disabled');

选中checked

checked属性表示选中,通常不可取消。

radio选中
html
<xy-radio checked>radio</xy-radio>

通常多个出现,有一个相同的name,表示同一组,可以通过name来获取当前组的选中(通过dom获取即可)。

ReactVueAngularOther获取选中状态
html
<xy-radio name="lib" checked>React</xy-radio>
<xy-radio name="lib">Vue</xy-radio>
<xy-radio name="lib">Angular</xy-radio>
<xy-radio name="lib">Other</xy-radio>

JavaScript操作getset

js
radio.checked;//获取
radio.checked = false;
radio.checked = true;
//原生属性操作
radio.setAttribute('checked','');
radio.removeAttribute('checked');
document.querySelector('xy-radio[name=lib][checked]').value

单选框组 xy-radio-group

表示同一组,支持以下特性

  • 设置和获取disabled
  • 设置和获取value
  • 支持change事件
禁用选中Php
HTMLCSSJavascriptPhpDart
html
<xy-radio-group name="lan" disabled value="CSS">
    <xy-radio>HTML</xy-radio>
    <xy-radio>CSS</xy-radio>
    <xy-radio>Javascript</xy-radio>
    <xy-radio>Php</xy-radio>
    <xy-radio>Dart</xy-radio>
</xy-radio-group>

JavaScript操作getset

js
radiogroup.value;//获取
radiogroup.value = 'CSS';
//原生属性操作
radiogroup.getAttribute('value');
radiogroup.setAttribute('value','CSS');

自定义样式::part(radio)

需要注意的是,xy-radio本身不包含任意样式,如果需要自定义单选框本身样式,需要深入到shadow dom中,这里暴露了内置伪元素::part(radio)用来自定义样式

内部结构如下(可查看控制台):

html
<xy-radio>
  # shadow-root
    <input type="radio" part="radio">
    <label>
      <slot></slot>
    </label>

checkbox 是一致的,下面介绍另一种自定义方式

比如,将 radio 完全隐藏,然后切换的时候改变文本样式

TIP

不要直接用display:none,这样会失去键盘访问

HTMLCSSJavascriptPhpDart
css
xy-radio::part(radio){
  position: absolute;
  clip-path: inset(100%);
}
xy-radio[checked]{
  color: var(--primary-color);
}

事件event

onchange

在切换完成时触发。

radio
html
<xy-radio onchange="console.log('当前状态checked:'+this.checked)">radio</xy-radio>
js
radio.onchange = function(ev){
    //获取checked的几种方式
    console.log(this.checked);
    console.log(ev.target.checked);
}

radio.addEventListener('change',function(ev){
    console.log(this.checked);
    console.log(ev.target.checked);
})

xy-radio-group支持change事件

HTMLCSSJavascriptPhpDart
js
radiogroup.onchange = function(ev){
    //获取value的几种方式
    console.log(this.value);
    console.log(ev.target.value);
}

radiogroup.addEventListener('change',function(ev){
    console.log(this.value);
    console.log(ev.target.value);
})

MIT License.