【问题标题】:Is it possible to transition placeholder text from beginning to end?是否可以从头到尾转换占位符文本?
【发布时间】:2019-04-29 19:31:53
【问题描述】:

我想在已知宽度(隐藏溢出)的文本输入中从头到尾转换一行动态占位符文本

现在我知道对于常规容器 div,我可以利用转换来转换正确的长度...

所以对于长度为 100 像素的容器,我可以使用以下命令过渡到文本末尾:transform: translateX(calc(100px - 100%)

div {
  width: 100px;
  border: 2px solid green;
  margin: 10px;
  padding: 5px;
}
div {
  white-space: nowrap;
  overflow: hidden;
}
span {
  display: inline-block;
  animation: 4s scrollText forwards;
}

@keyframes scrollText {
  to {
      transform: translateX(calc(100px - 100%));
  }
}
<div><span>some really really really long text here</span></div>

我想知道是否可以使用placeholder pseudo element 使用占位符文本来实现上述效果。

所以我尝试了以下方法:

input {
  width: 100px;
  border: 2px solid green;
  margin: 10px;
  padding: 5px;
}

input::placeholder {
  color: red;
  animation: 4s scrollText;
  transform: translateX(0);
}

@keyframes scrollText {
  from {
      transform: translateX(0);
  }
  to {
      transform: translateX(calc(100px - 100%));
  }
}
<input type="text" placeholder="some really really really long text here">

...但是由于占位符伪元素上可用属性的限制,上述 sn-p 不起作用

也适用于::first-line pseudo-element 的所有属性 适用于 ::placeholder 伪元素。

很遗憾,transform1 没有出现在 that list 中。

所以我想知道是否有另一种方法可以实现这一点 - 可能使用占位符伪元素支持的其他属性。


  1. 奇怪的是,在没有 calc 函数和动画的情况下,transform 属性似乎(在某种程度上)在 Chrome 上有效。

input {
  width: 100px;
  border: 2px solid green;
  margin: 10px;
  padding: 5px;
}

input::placeholder {
  color: red;
  transform: translateX(-50%);
}
<input type="text" placeholder="some really really really long text here">

【问题讨论】:

  • 一个需要“滚动”的长度的占位符是一个 UX 无法以恕我直言开始......
  • @04FS 我同意,但我还是想知道这是否可能

标签: css placeholder


【解决方案1】:

您可以使用额外的包装器来模拟这一点,而无需在输入元素上真正使用占位符:

input {
  width: 100px;
  border: 2px solid green;
  padding: 5px;
  vertical-align:top;
  background:transparent; /* a transparent background to show the pseudo element */
}


.input {
  display:inline-block;
  margin: 10px;
  position:relative;
  z-index:0;
  overflow:hidden;
}

.input:before {
  content:attr(placeholder);
  position:absolute;
  left:5px;
  top:5px;
  white-space:nowrap; /* no line break */
  color: red;
  pointer-events:none; /* avoid any interaction */
  animation: 4s scrollText forwards;
  z-index:-1;
}

@keyframes scrollText {
  to {
      transform: translateX(calc(100px - 100%));
  }
}

/* hide the before on focus */
.input:focus-within:before{
   visibility:hidden;
}

/* add background to hide the before when there is text and no focus*/
input:not(:placeholder-shown) {
  background:#fff;
}
<div class="input" placeholder="some really really really long text here">
<input type="text" placeholder=" "> <!-- needs an empty placeholder for :placeholder-shown -->
</div>

【讨论】:

  • 好的,谢谢,我希望有一种方法可以在没有包装元素的情况下做到这一点......但我想不会。
  • @Danield 是的,我不这么认为,但是由于转换适用于占位符,您可能可以考虑 JS 通过增加转换来为其设置动画
猜你喜欢
  • 2018-01-24
  • 1970-01-01
  • 2021-01-12
  • 2016-08-29
  • 2021-11-03
  • 1970-01-01
  • 1970-01-01
  • 2016-10-07
  • 1970-01-01
相关资源
最近更新 更多