自定义DIV实现的圆角下拉选择框展开时边框衔接问题求解
完全不需要将选择框的圆角改为直角,通过少量CSS修改即可实现圆角状态下的自然衔接效果,修改方案如下:
问题原因
当前代码存在两处导致衔接异常的问题:
- 触发框和下拉列表都带完整边框,拼接时会出现重叠的双边框
- 展开状态下触发框的底部圆角未隐藏,和下拉列表的直角顶部拼接会露出缝隙
具体修改代码
你只需要在原有CSS基础上新增/修改以下规则即可:
/* 新增:展开状态下触发框去掉底部圆角,和下拉列表无缝衔接 */ .custom-select.open .custom-select__trigger { border-bottom-left-radius: 0; border-bottom-right-radius: 0; border-bottom-color: transparent; position: relative; z-index: 3; } /* 修改下拉列表样式:向上偏移1px,去掉顶部边框 */ .custom-options { /* 原有属性保留,修改/新增以下属性 */ top: calc(100% - 1px); border-top: none; }
修改后展开时触发框底部会自动变成直角,收起时恢复完整圆角,下拉列表向上偏移1px刚好和触发框底部对齐,不会出现双边框或者缝隙。
额外优化建议(非必须)
你当前的JS逻辑存在重复绑定事件的问题:每次点击选择框都会给所有选项重新绑定一次click事件,多次点击后会触发多次重复逻辑。可以把option的绑定逻辑移到外层,只绑定一次:
// 选项点击事件只绑定一次 for (const option of document.querySelectorAll(".custom-option")) { option.addEventListener('click', function() { if (!this.classList.contains('selected')) { this.parentNode.querySelector('.custom-option.selected').classList.remove('selected'); this.classList.add('selected'); this.closest('.custom-select').querySelector('.custom-select__trigger span').textContent = this.textContent; } }) } // 只保留切换展开状态的逻辑 document.querySelector('.custom-select-wrapper').addEventListener('click', function() { this.querySelector('.custom-select').classList.toggle('open'); })
内容的提问来源于stack exchange,提问作者Sofia Lazrak
相关产品推荐
相关产品推荐

