首页 > 解决方案 > 如何在 CSS 中使父元素(跨度)对子元素(输入)进行转换?

问题描述

我想为输入框做一个很酷的效果。我希望发生这种情况:

当用户点击输入框时,输入边框的顶部(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>

请有人告诉我如何能够与输入框进行交互并让跨度边框在输入框上明显滑动?

标签: htmlcssfrontendtransformtransition

解决方案


添加背景:对输入字段透明。


推荐阅读