本文介绍一种巧妙的方法,将选择控件转变为类似组合锁或iOS日期选择器的拨盘式交互。长长的选择列表,例如国家选择,常常令人不胜其烦,此方法可有效解决此问题。
核心思想是:利用滚动操作选择选项,而非传统的点击选择。我们并非从零开始构建自定义控件,而是巧妙地利用语义化的表单控件——单选按钮。
HTML结构如下,使用嵌套单选按钮的标签组:
<label for="madrid"> Madrid <abbr>MAD</abbr> </label> <label for="malta"> Malta <abbr>MLA</abbr> </label>
关键在于CSS样式的控制,实现对选项大小和间距的精确管理。以下是一些基础样式:
.scroll-container { /* 尺寸和布局 */ \--itemHeight: 60px; \--itemGap: 10px; \--containerHeight: calc((var(--itemHeight) * 7) + (var(--itemGap) * 6)); width: 400px; height: var(--containerHeight); align-items: center; row-gap: var(--itemGap); border-radius: 4px; /* 样式 */ \--topBit: calc((var(--containerHeight) - var(--itemHeight))/2); \--footBit: calc((var(--containerHeight) + var(--itemHeight))/2); background: linear-gradient( rgb(254 251 240), rgb(254 251 240) var(--topBit), rgb(229 50 34 / .5) var(--topBit), rgb(229 50 34 / .5) var(--footBit), rgb(254 251 240) var(--footBit)); box-shadow: 0 0 10px #eee; }
样式说明:
--itemHeight
:每个选项的高度。--itemGap
:选项之间的间距。--containerHeight
:容器高度,确保最多显示七个选项(奇数个选项使选中项居中)。--topBit
和 --footBit
变量定义渐变色停靠点,视觉上突出选中项区域。使用Flexbox布局垂直排列选项:
.scroll-container { display: flex; flex-direction: column; /* 其他样式 */ }
启用CSS滚动捕捉:
.scroll-container { overflow-y: scroll; scroll-snap-type: y mandatory; overscroll-behavior-y: none; /* 其他样式 */ }
scroll-snap-type: y mandatory;
确保滚动停止在选项上。overscroll-behavior-y: none;
阻止滚动溢出。
选项样式:
.scroll-item { /* 尺寸和布局 */ width: 90%; box-sizing: border-box; padding-inline: 20px; border-radius: inherit; /* 样式和字体 */ background: linear-gradient(to right, rgb(242 194 66), rgb(235 122 51)); box-shadow: 0 0 4px rgb(235 122 51); font: 16pt/var(--itemHeight) system-ui; color: #fff; input { appearance: none; } abbr { float: right; } /* 机场代码 */ /* 选中状态样式 */ &:has(:checked) { background: rgb(229 50 34); } }
scroll-snap-align: center;
使选项居中对齐。pointer-events: none;
阻止点击选择,仅通过滚动选择。
JavaScript代码用于监听滚动事件,将滚动到中心的选项设置为选中状态:
let observer = new IntersectionObserver(entries => { entries.forEach(entry => { with(entry) if(isIntersecting) target.children[1].checked = true; }); }, { root: document.querySelector(`.scroll-container`), rootMargin: `-51% 0px -49% 0px` }); document.querySelectorAll(`.scroll-item`).forEach(item => observer.observe(item));
IntersectionObserver
API用于检测元素是否进入视口。
通过以上步骤,即可创建一个通过滚动选择选项的表单控件。 如果需要页面加载时预选一个选项,可以通过JavaScript获取其位置并使用scrollTo()
方法滚动到该位置。
参考链接和进一步阅读:
flex
property (CSS-Tricks)scrollTo()
(MDN)(GitHub页面演示链接和视频链接将在此处补充,因为我无法直接访问和嵌入外部资源。)
以上是如何制作'选择”表单控件的详细内容。更多信息请关注PHP中文网其他相关文章!