我有一个适用于输入框的浮动标签脚本。我如何更改下面的脚本以使其适用于textarea?我将$ fields.on(" textarea",floatLabel)添加到脚本中,但它没有工作。有什么帮助吗?
(function($){
var $fields = $(".floatLabel");
// when data is entered...
$fields.on("input", floatLabel);
$fields.on("textarea", floatLabel);
// Check the text fields as soon as the document loads for data that
// may have been added upon load
floatLabel();
function floatLabel(){
$fields.each(function(i, f){
var $field = $(f);
if($field.val().trim() === "" || $field.val() === "blank"){
$field.next().removeClass("active");
} else {
$field.next().addClass("active");
}
});
}
})(jQuery);
CSS
.controls label.active {
position:relative;
top: -50px;
left:-175px;
color: #555;
background-color: white;
}
.controls label {
position: relative;
top:0px;
left:-175px;
color: #999;
font-size: 18px;
display: inline-block;
padding-left: 5px;
padding-right: 5px;
margin: 0;
font-weight: 400;
background-color: rgba(255, 255, 255, 0);
pointer-events: none;
transition: color 0.3s, top 0.3s, background-color 0.8s;
}
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="top-row">
<div class="field-wrap">
<div class="controls">
<input type="text" class="floatLabel" name="property_address" value="<?php echo $address?>" required>
<label for="property_address">Street Address</label>
</div>
</div>
<div class="two-row">
<div class="field-wrap">
<div class="controls">
<textarea name="comments" class="floatLabel">value="<?php echo $comments?>"</textarea>
<label for="comments"></label>
</div>
</div>
</div>
</div>
答案 0 :(得分:1)
你误解了
的使用$fields.on("Input")
这并不意味着&#34;在输入框&#34;但在输入事件上,如在接收输入中。所以把它改成&#34; textarea&#34;什么都不做,因为那个事件不存在。所以你应该删除那一行。
此外,当您调用您的函数时,您可以直接调用它:
$fields.on("input", floatLabel())
你不需要额外的floatLabel()。因为脚本加载后会立即执行。
编辑:我不知道textarea是否有输入&#39;事件。但也许你应该看一下keyup事件?