我在页面上有一个搜索按钮,当用户按下搜索按钮时,搜索栏就会出现在屏幕上,我也想将输入设置为焦点。我可以用纯 CSS3 做到这一点吗?
代码如下:
<input type="checkbox" id="Search_Button" /> <!-- Opens Search Bar -->
<label for="Search_Button">
<div id="Search_Container" class="Button_Container">
<img src="SVG/Search.svg" class="Button" id="Search" />
</div>
</label>
在这里您可以看到 CSS 样式,以便将搜索栏推离屏幕:
#Search_Box {
position: absolute;
width: 100vw;
height: 8vh;
background-color: #38D1A9;
transform: translate3d(0, -8vh, 0);
transition: transform .2s ease-out;
}
这是下拉的搜索框:
<div id="Search_Box">
<input type="search" name="Search" id="Search_Input" placeholder="Search" />
</div>
那么问题来了。我显示了一个搜索图标。当按下搜索图标时,它会打开其中包含搜索输入的“Search_Box”。我想,当按下该搜索图标时,立即使该搜索框成为焦点。
标签技术的问题是,虽然它完全按预期工作,但搜索图标已经在标签内(它位于其中的标签是为了让搜索框进入视野),所以我不会能够将其包裹在另一个标签中。
我试着这样做:
#Search_Button:checked ~ div #Search_Input {
cursor: pointer;
}
我试着说当 Search_Button 被选中时,它会使搜索输入成为焦点,但这绝对不是这样做的方法。我尽量避免使用 JS,因为我在移动设备上工作。
对于任何混淆,我深表歉意!
最佳答案
通过将 label
元素与 input
元素相关联,您可以使用原生 HTML 行为实现此目的。将 label
元素的 for
属性设置为等于 input
元素的 id
属性值。当 label
元素被点击时,input
元素将被聚焦。
没有 JavaScript 的例子:
label {
-webkit-appearance: button;
-moz-appearance: button;
appearance: button;
padding: 1px 6px;
}
<label for="focus-input">Button</label>
<p>Other elements...</p>
<input type="text" id="focus-input" />
值得一提的是,上面的 CSS 不是必需的。添加它只是为了使 label
元素出现在按钮上。随意设置 label
元素的样式。在某些情况下,您甚至可以将其包裹在其他元素周围。
具有不同样式的替代示例:
label {
border: 1px solid #ccc;
display: inline-block;
padding: 6px 12px;
cursor: pointer;
}
<label for="focus-input">Button</label>
<p>Other elements...</p>
<input type="text" id="focus-input" />
使用 JavaScript 的替代示例:
document.querySelector('button').addEventListener('click', function () {
document.getElementById('focus-input').focus();
});
<button>Button</button>
<p>Other elements...</p>
<input type="text" id="focus-input" />
关于html - 当我使用 CSS3 按下按钮时,将文本输入设置为焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34164074/