【问题标题】:Floating Placeholder浮动占位符
【发布时间】:2023-03-19 09:24:01
【问题描述】:

我正在尝试为页面上的表单实现浮动标签。

我参考了几个来源,并在 codepen 和 Fiddle 中看到了这个链接。

我可以实现这一点,但这些方法需要重新执行所有表单,因为我需要将输入字段包装在 div 或字段集中并添加标签。有没有办法使用 jQuery 并直接定位占位符?

我知道这个问题非常高级。我很抱歉。

【问题讨论】:

标签: jquery css user-interface frontend user-experience


【解决方案1】:

我在这里为您准备了一个 jQuery 解决方案 - 它只需要您为每个表单元素添加一个 'placeholder="placeHolderTextGoesHere"' 属性。

$("input").each(function(e){

    $(this).wrap('<fieldset></fieldset>');
    var tag = $(this).attr("placeholder");
    $(this).attr("placeholder","");
    $(this).after('<label for="name">'+tag+'</label>');
});

我们正在做的是找到所有输入 - 将它们包装在一个字段集中,然后在之后添加一个标签 - 我们使用占位符标记作为非 JS 访问者的后备,如果允许 JS,则将其设置为“”在抓住它的价值之后。

$("input").each(function(e) {
  $(this).wrap('<fieldset></fieldset>');
  var tag = $(this).attr("placeholder");
  //var tag= $(this).data("tag");
  $(this).attr("placeholder", "");
  $(this).after('<label for="name">' + tag + '</label>');
});

$('input').on('blur', function() {
  if (!$(this).val() == "") {
    $(this).next().addClass('stay');
  } else {
    $(this).next().removeClass('stay');
  }
});
* {
  box-sizing: border-box;
}
body {
  background: #eee;
}
form {
  background: #fff;
  padding: 2em;
  width: 30em;
  margin: 5em auto;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, .25);
}
fieldset {
  border: none;
  position: relative;
  font-family: arial, sans-serif;
}
input {
  width: 20em;
  padding: 1em 1em .8em 1em;
  width: 100%;
  font-size: 1.2em;
  border: 1px solid #aaa;
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, .15);
  border-radius: 2px;
}
input:focus {
  outline: none;
  background: #fbfbe9;
}
input + label {
  display: block;
  cursor: text;
  color: #777;
  transition: .15s ease-out all;
  position: absolute;
  top: 1.8em;
  left: 2.3em;
}
input:focus + label,
label.stay {
  top: 1em;
  left: 3em;
  font-size: .7em;
  font-weight: bold;
  color: #139dd7;
  transition: .15s ease-out all;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
  <input type="text" placeholder="name" name="" id="name" />
  <input type="text" placeholder="email" name="" id="email" />
</form>

【讨论】:

  • Thank 非常接近我想要的,只需对现有代码(字段集类的 CSS)进行最小的更改。谢谢。
猜你喜欢
  • 1970-01-01
  • 2019-05-22
  • 2022-12-13
  • 2017-03-10
  • 1970-01-01
  • 1970-01-01
  • 2018-08-21
  • 1970-01-01
  • 2019-02-22
相关资源
最近更新 更多