select多选的value属性重置与样式自定义演示页面
展示
代码
-
HTML:
<select id="select" multiple> <option value="1">选项1</option> <option value="2">选项2</option> <option value="3">选项3</option> <option value="4">选项4</option> <option value="5">选项5</option> </select>
-
CSS:
select[multiple] { padding: 0; scrollbar-width: thin; border: 1px solid #a2a9b6; background-color: #2a80eb; min-width: 150px; outline: none; line-height: 1.25rem; border-radius: 4px; overflow: auto; } option { padding: .375rem 2rem .375rem 1rem; box-shadow: inset 0 1px #ededef; color: #4c5161; font-size: .875rem; background-color: #fff; } option::after { content: ' ✓'; color: transparent; } option:hover { background-color: #f0f7ff; } option:checked { background-color: #e0f0ff; mix-blend-mode: lighten; } option:checked::after { color: currentColor; }
-
JS:
// 让多选框的value属性返回所有选中项的值 Object.defineProperty(HTMLSelectElement.prototype, 'value', { configurable: true, enumerable: true, writeable: true, get: function () { return [...select.selectedOptions].map(option => option.value).join(); }, set: function (value) { [...this.options].some((option) => { if (value.split(',').includes(option.value)) { option.selected = true; // 单选第一个匹配即选中 if (!this.multiple) { return true; } } else if (this.multiple) { option.selected = false; } }); } }); select.onchange = function () { console.log('选中的值:' + this.value); }