使用popover属性模拟select下拉实例页面

回到相关文章 »

效果:

  • 请选择
  • 选项1
  • 选项2
  • 选项3
  • 选项4
  • 代码:

    CSS代码:
    /* 略,右键-查看源代码进行查看 */ 
    HTML代码:
    <div class="ui-select">
        <button id="button" class="ui-select-button" popovertarget="select">
            <span class="ui-select-text">请选择</span>
        </button>
        <menu id="select" popover class="ui-select-datalist">
            <li class="ui-select-datalist-li"><input type="radio" name="type" value="">请选择</li>
            <li class="ui-select-datalist-li"><input type="radio" name="type" value="1">选项1</li>
            <li class="ui-select-datalist-li"><input type="radio" name="type" value="2">选项2</li>
            <li class="ui-select-datalist-li"><input type="radio" name="type" value="3" disabled>选项3</li>
            <li class="ui-select-datalist-li"><input type="radio" name="type" value="4">选项4</li>
        </menu>
    </div>
    JS代码:
    button.onclick = function () {
        const bounding = this.getBoundingClientRect();
    
        this.parentElement.style.setProperty('--top', bounding.bottom + window.pageYOffset);
        this.parentElement.style.setProperty('--left', bounding.left + window.pageXOffset);
        this.parentElement.style.setProperty('--width', bounding.width);
    };
    select.onclick = function (event) {
        if (event.target.type == 'radio') {
            this.hidePopover();
            // 选择文字内容更新
            button.firstElementChild.textContent = event.target.parentElement.textContent;
        }
    }