【发布时间】:2026-01-08 13:55:02
【问题描述】:
我想为输入框做一个很酷的效果。我希望这种情况发生:
当用户点击输入框时,输入边框的顶部(border-top)优雅地移动到输入边框的底部(border-bottom)。
但是,我很快了解到您不能将元素边框顶部移动到边框底部的位置。
所以我提出了一个可行的解决方案(有点)!通过将输入放置在 span 元素内,我可以将 span 的边框顶部向下转换,以产生输入边框顶部向下移动的错觉。 唯一的问题是,当 span 的边框移到输入框上方时,您将看不到它,因为输入框的 z-index 更大(我猜)。
这是我的解决方案:
<!DOCTYPE html>
<html>
<head>
<style>
/* input box - no border, no ouline, and a transition to move up (to cancel out the transtion made by the parent).*/
input{
border: 1px solid transparent;
outline: none;
transition: transform 2s;
}
/* span - red border and a transition to move down */
span{
display: inline-block;
content: '';
border-top: 1px solid red;
transition: transform 2s;
}
/* on focus of the child element of span - transform span down */
span:focus-within{
transform: translate(0%, 30px);
}
/* while active or focused on input - transform input up*/
input:active, input:focus {
transform: translate(0%, -30px);
}
</style>
</head>
<body>
<span>
<input type='text' placeholder='john doe'/>
</span>
</body>
</html>
所以,很自然,我认为解决方案是为 span 元素授予更高的 z-index。 问题是,如果我这样做,那么整个事情都会中断,因为 input 是 span 的子项......所以,如果 span 有更高的索引,那么我永远无法在输入框中输入任何文本。
如下图:
<!DOCTYPE html>
<html>
<head>
<style>
/* input box - no border, no ouline, and a transition to move up (to cancel out the transtion made by the parent).*/
input{
border: 1px solid transparent;
outline: none;
transition: transform 2s;
position: relative;
z-index: -1;
}
/* span - red border and a transition to move down */
span{
display: inline-block;
content: '';
border-top: 1px solid red;
transition: transform 2s;
position: relative;
z-index: 1;
}
/* on focus of the child element of span - transform span down */
span:focus-within{
transform: translate(0%, 30px);
}
/* while active or focused on input - transform input up*/
input:active, input:focus {
transform: translate(0%, -30px);
}
</style>
</head>
<body>
<span>
<input type='text' placeholder='john doe'/>
</span>
</body>
</html>
请有人告诉我如何能够与输入框进行交互,并让跨度边框在输入框上明显滑动?
【问题讨论】:
-
找到了我真正想要的那个:codepen.io/Takumari85/pen/RaYwpJ
-
感谢您分享第二个链接,这些都是一些了不起的想法!但不是我想要的,我最终弄明白了。
-
我的链接丢失时间最长,但你提醒我,我找到了,所以也谢谢你:)
标签: html css frontend transform transition