JavaScript - 使用jQuery获取hasClass()的当前焦点元素

时间:2016-08-20 09:59:09

标签: javascript jquery

我知道这对你来说只是一个简单的问题,但在这里我很难解决自己的问题。

就我而言,我有几个文本字段可以在字段本身聚焦时更改字段边框和标签文本的颜色,并在未聚焦时还原更改。所以我使用了以下代码:(参见我的demo

$(function() {
  $(".field").focus(function() { /* ... */ });
  $(".field").blur(function() { /* ... */ });
});

但由于我指的是类.field,所有具有此类的元素都会受到影响所以我认为我必须使用类.field设置当前活动元素,以便其他元素将被排除在外。我使用下面的代码,但它不起作用(我甚至不知道我的想法是否正确):

var current = $(document.activeElement).hasClass(".field");
$(current).focus(function() { /* ... */ });
$(current).blur(function() { /* ... */ });

如果有另一种解决方法,请告诉我如何。

希望你能帮助我。

感谢。

2 个答案:

答案 0 :(得分:0)

您可以将$(“。field”)选择器更新为$(this)以选择字段和$(this).next()以在模糊和焦点功能中选择字段的标签。 选中的字段和下一个标签将被选中,请参阅以下代码段:

$(function() {
  $(".field").focus(function() {
    /* when field with or without value is focused, add these classes */
    if ($(this).val().length || $(".field").val().length == "") {
      $(this).addClass("field-is-focused");
      $(this).next().addClass("label-is-focused");
    }
  });
  $(".field").blur(function() {
    /* when field with or without value is not focused, remove added classes */
    if ($(this).val().length || $(".field").val().length == "") {
      $(this).removeClass("field-is-focused");
       $(this).next().removeClass("label-is-focused");
    }
  });
});
fieldset {
  border: 2px solid #ccc;
  padding-top: 20px;
  padding-bottom: 20px;
}
.label {
  float: left;
  margin-right: 5px;
}
.field {
  border: 2px solid #ccc;
  padding: 0 5px;
  height: 22px;
  margin-bottom: 10px;
}
.field:focus {
  outline: 0;
  outline-offset: 0;
}

/*---------------------------------*/

.field-is-focused {
  border-color: blue;
}
.label-is-focused {
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
  <head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width"/>
	<title>jQuery - Get current focused element</title>
        <script src="https://code.jquery.com/jquery.min.js"></script>
  </head>
  <body>
	<form>
	  <fieldset>
		<!-- input email type field -->
		<input type="email" class="field">
		<label class="label">Email</label>

		<!-- input password type field -->
		<input type="password" class="field">
		<label class="label">Password</label>
		
		<!-- textarea field -->
		<textarea class="field"></textarea>
		<label class="label">Comment</label>
	  </fieldset>
	</form>
  </body>
</html>

答案 1 :(得分:0)

尝试使用焦点CSS属性为.field。

.field :focus{
/*your style change*/
}

这可能会消除焦点/模糊事件的功能。希望这有帮助!