我偶然发现了这种情况:当输入字段的宽度由按钮控制时,自动对焦不起作用。对点击的关注并不起作用,因为它会向后触发宽度动画...
我怀疑在某个地方出现了一个愚蠢的等级错误,所以这里有一个代码来展示我的所作所为:https://codepen.io/anon/pen/qPqXdp
对不起,我担心的基本麻烦......
.center {
margin: 0 auto;
width: 700px;
}
.search-wrap {
position: relative;
}
.search-button {
width: 50px;
height: 50px;
position: absolute;
right: 0;
}
.search-form {
height: 51px;
width: 0;
position: absolute;
right: 50px;
top: 0;
-webkit-transition: width 400ms ease;
transition: width 400ms ease;
}
.search-form .search-field {
height: 100%;
width: 100%;
}
.search-button:focus+.search-form {
width: 650px;
right: 50px;
}

<div class="center">
<div class="search-wrap">
<button class="search-button">?</button>
<form class="search-form">
<label>
<input type="search" class="search-field" autofocus/>
</label>
</form>
</div>
</div>
&#13;
答案 0 :(得分:0)
autofocus
属性在您的示例中正常运行。问题是,当您点击该按钮时,焦点会从input
更改为button
。 您一次只能关注一个元素,因此无法按照您希望的方式进行操作。但是,您可以使用:checked
伪类来实现相同的结果:
.center {
margin: 0 auto;
width: 700px;
}
.search-wrap {
position: relative;
}
.change-width {
width: 50px;
height: 50px;
position: absolute;
right: -10px;
}
.search-form {
height: 51px;
width: 0;
position: absolute;
right: 50px;
top: 0;
-webkit-transition: width 400ms ease;
transition: width 400ms ease;
}
.search-form .search-field {
height: 100%;
width: 100%;
}
#change:checked + .search-form {
width: 650px;
right: 50px;
}
#change {
display: none;
}
<div class="center">
<div class="search-wrap">
<label for="change" class="change-width">?</label>
<input id="change" type="checkbox">
<form class="search-form">
<label>
<input type="search" class="search-field" id="input">
</label>
</form>
</div>
</div>
现在你可以专注于点击。由于点击页面上的任意位置(在这种情况下为autofocus
),label
仍然无效。
答案 1 :(得分:0)
我不认为仅HTML和CSS就有办法。
所以我找到的解决方案是使用Javascript来增加按钮的宽度并同时专注于输入字段。
const searchWrap = document.querySelector('.search-wrap');
const searchField = document.querySelector('.search-field');
const searchBtn = document.querySelector('.search-button');
searchBtn.addEventListener('focus', function () {
searchWrap.classList.toggle('active');
searchField.focus();
});
.center {
margin: 0 auto;
width: 200px;
}
.search-wrap {
position: relative;
}
.search-button {
width: 50px;
height: 50px;
position: absolute;
right: 0;
}
.search-form {
height: 51px;
width: 0;
position: absolute;
right: 50px;
top: 0;
-webkit-transition: width 400ms ease;
transition: width 400ms ease;
}
.search-form .search-field {
height: 100%;
width: 100%;
}
.active .search-form {
width: 250px;
right: 50px;
}
<div class="center">
<div class="search-wrap">
<button class="search-button">?</button>
<form class="search-form">
<label>
<input type="search" class="search-field">
</label>
</form>
</div>
</div>
<script>
</script>