动画取决于输入框是否为空并留在那里?

时间:2015-10-30 11:47:04

标签: javascript jquery html css input

我正在尝试创建一个输入框,看起来它有一个占位符,表示用户名,但是当选中该框时,它会移动并更改为更暗的颜色以类似于标签。我遇到的问题是,只要我将鼠标悬停在方框上,它就会完成动画,然后立即撤消它,将文本放回看起来像占位符。我还想制作我的Javascript / JQuery代码,这样如果框中有任何键入内容,文本将作为标签保留,即使没有被选中也不会再回到占位符。我的另一个问题是我不知道JQuery命令来判断是否选择了输入框。我提供下面的所有代码以及指向CodePen的链接

<div id='inputdiv'>
  <input id='textinp'>
</div>
<h4>Username</h4>


#textinp {
  border: none;
  width: 200px;
  height: 30px;
  font-size: 20px;
  margin-left: 5px;
  font-family: 'Roboto', sans-serif;
  background: rgba(0, 0, 0, 0);
}

input:focus {
  outline: 0;
}

#inputdiv {
  width: 200px;
  height: 32px;
  margin: 0 auto;
  margin-top: 70px;
  border-top: 1px solid black;
  border-right: none;
  border-left: 1px solid black;
  border-bottom: none;
  z-index: -2;
}

h4 {
  font-family: 'Roboto', sans-serif;
  font-size: 20px;
  position: relative;
  bottom: 53px;
  left: 575px;
  color: #C2C2C2;
  z-index: -1;
}


$(document).ready(function() {
  $("#inputdiv").mouseenter(function() {
    $("h4").animate({
      left: '470px',
      color: '#00000'
    });
    if ($('#textinp').val() == '') {
      $("h4").animate({
        left: '580px',
        color: '#C2C2C2'
      });
    }
  });
});

CodePen

1 个答案:

答案 0 :(得分:1)

尝试使用hover()方法。作为第一个参数定义要在hoverIn上执行的函数(在鼠标输入时),作为第二个 - 在hoverOut上执行的函数(在鼠标离开时)。

以下是您更新的示例: http://codepen.io/anon/pen/LprybQ

相关问题