[英]Set text input to focus when I press a button with CSS3
我在页面上有一个搜索按钮,当用户按下搜索按钮时,搜索栏进入屏幕,我也想将输入设置为焦点。 我可以用纯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
element id
属性值。 单击label
元素时,将关注input
元素。
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" />
document.querySelector('button').addEventListener('click', function () { document.getElementById('focus-input').focus(); });
<button>Button</button> <p>Other elements...</p> <input type="text" id="focus-input" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.