当我按下带有CSS3的按钮时,将文本输入设置为焦点

Kod*_* R. 4 html css html5 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>
Run Code Online (Sandbox Code Playgroud)

在这里你可以看到CSS样式,以便搜索栏被推离屏幕:

#Search_Box {
    position: absolute; 
    width: 100vw;
    height: 8vh;
    background-color: #38D1A9;
    transform: translate3d(0, -8vh, 0);
    transition: transform .2s ease-out;
}
Run Code Online (Sandbox Code Playgroud)

这是下拉的搜索框:

<div id="Search_Box">
    <input type="search" name="Search" id="Search_Input" placeholder="Search" />
</div>
Run Code Online (Sandbox Code Playgroud)

所以这就是问题所在.我显示了一个搜索图标.当按下搜索图标时,它会关闭其中包含搜索输入的"Search_Box".我想,当按下该搜索图标时,立即使该搜索框成为焦点.

标签技术的问题在于,虽然它完全按预期工作,但搜索图标已经在标签内(它位于里面的标签是将搜索框放入视图中),所以我将无法包装它在另一个标签.

我试着这样做:

#Search_Button:checked ~ div #Search_Input {
    cursor: pointer;
}
Run Code Online (Sandbox Code Playgroud)

我试过说当检查Search_Button时,它会使搜索输入成为焦点,但绝对不是这样做的.我试图避免使用JS,因为我正在使用移动设备.

我真的为任何困惑道歉!

Jos*_*ier 6

您可以通过将label元素与input元素相关联来实现本机HTML行为.将label元素的for属性设置为等于input元素id属性值.当label被点击的元素,该input元素将被重点.

没有JavaScript的示例:

label {
  -webkit-appearance: button;
  -moz-appearance: button;
  appearance: button;
  padding: 1px 6px;
}
Run Code Online (Sandbox Code Playgroud)
<label for="focus-input">Button</label>
<p>Other elements...</p>
<input type="text" id="focus-input" />
Run Code Online (Sandbox Code Playgroud)

值得一提的是,上面的CSS不是必需的.仅添加它才能使label元素出现在按钮上.您可以根据label需要随意设计元素.在某些情况下,您甚至可以将其包裹在其他元素周围.

不同样式的替代示例:

label {
  border: 1px solid #ccc;
  display: inline-block;
  padding: 6px 12px;
  cursor: pointer;
}
Run Code Online (Sandbox Code Playgroud)
<label for="focus-input">Button</label>
<p>Other elements...</p>
<input type="text" id="focus-input" />
Run Code Online (Sandbox Code Playgroud)


JavaScript的替代示例:

document.querySelector('button').addEventListener('click', function () {
  document.getElementById('focus-input').focus();
});
Run Code Online (Sandbox Code Playgroud)
<button>Button</button>
<p>Other elements...</p>
<input type="text" id="focus-input" />
Run Code Online (Sandbox Code Playgroud)