【问题标题】:On input focus change the font size of label在输入焦点上更改标签的字体大小
【发布时间】:2018-04-23 02:26:47
【问题描述】:

我正在尝试在输入焦点上实现浮动标签,因为这个带有样式组件: https://jsfiddle.net/273ntk5s/3650/

但我的表单是动态加载的,所以先加载标签,然后再加载输入。之后加载输入类型文本时,输入焦点更改不起作用。有没有办法做到这一点?我也使用过 jQuery,仍然没有运气。 CSS:

var oldSize;
$('#FirstName').focus(function() {
  oldSize = $("label[for='FirstName']").css('font-size');
  $("label[for='FirstName']").css('font-size', 12);
});
$('#FirstName').blur(function() {
  $("label[for='FirstName']").css('font-size', oldSize);
});
.inputText {
  font-size: 14px;
  width: 200px;
  height: 35px;
}

.floating-label {
  position: absolute;
  pointer-events: none;
  font-size: 14px;
  transition: 0.2s ease all;
}
input[id='FirstName']:focus + .floating-label
{
    font-size: 11px;
}
<div>
  <label for="FirstName" class="mktoLabel mktoHasWidth floating-label" style="width: 100px;">First name:</label>
  <input id="FirstName" name="FirstName" maxlength="255" type="text" class="mktoField mktoTextField mktoHasWidth mktoRequired mktoInvalid inputText" style="width: 150px;">

</div>

【问题讨论】:

  • 在你的小提琴中添加 jQuery 后它工作正常 ..

标签: javascript jquery html css input


【解决方案1】:

font-size 接受##px 格式的值。单靠数字是行不通的。您还需要在小提琴中正确包含 jQuery。

var oldSize;
$('#FirstName').focus(function() {
  oldSize = $("label[for='FirstName']").css('font-size');
  $("label[for='FirstName']").css('font-size', '42px');
});
$('#FirstName').blur(function() {
  $("label[for='FirstName']").css('font-size', oldSize);
});
.inputText {
  font-size: 14px;
  width: 200px;
  height: 35px;
}

.floating-label {
  position: absolute;
  pointer-events: none;
  font-size: 14px;
  transition: 0.2s ease all;
}
input[id='FirstName']:focus + .floating-label
{
    font-size: 11px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <label for="FirstName" class="mktoLabel mktoHasWidth floating-label" style="width: 100px;">First name:</label>
  <input id="FirstName" name="FirstName" maxlength="255" type="text" class="mktoField mktoTextField mktoHasWidth mktoRequired mktoInvalid inputText" style="width: 150px;">

</div>

【讨论】:

  • 这是有效的,但我遇到的另一个问题是输入类型的文本边框在我的表单中的焦点上也有一点上移。我希望输入类型的文本边框底部是固定的,不要移动到任何地方,只是改变字体大小。
猜你喜欢
  • 1970-01-01
  • 2014-02-04
  • 1970-01-01
  • 1970-01-01
  • 2018-12-01
  • 2020-06-02
  • 2020-07-19
  • 2020-06-28
  • 2015-10-27
相关资源
最近更新 更多