【问题标题】:How to auto-hide placeholder text in input field using jquery如何使用jquery在输入字段中自动隐藏占位符文本
【发布时间】:2017-08-01 15:02:53
【问题描述】:
我在这里有这段代码,它的作用是在焦点上隐藏占位符字段并使用 jquery 在模糊上显示它们,但我需要有人逐行向我解释这段代码,因为我是初学者
$(function() {
'use strict';
// hide placeholder on form focus
$('[placeholder]').focus(function() {
$(this).attr('data-text', $(this).attr('placeholder'));
$(this).attr('placeholder', '');
}).blur(function() {
$(this).attr('placeholder', $(this).attr('data-text'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<h4 class="text-center"> Admin Login </h4>
<input type="text" name="user" placeholder="Username" autocomplete="off">
<input type="password" name="pass" placeholder="Password" autocomplete="new-password">
<input type="submit" value="Login">
</form>
【问题讨论】:
标签:
javascript
jquery
html
【解决方案1】:
$(function() {})....
//is an anonymous function which gets called when js file gets loaded in the browser.
$('[placeholder]')
//Provides collections of elements objects having placeholder inside the form.
$('[placeholder]').focus(callback)
//This statement will bind the focus event to all the elements which supports placeholder.
callback()
//This is a function which gets called when above event gets fired.
//Inside call back in above code two below statements are written
$(this).attr('data-text', $(this).attr('placeholder'));
// Above satement will pick text given in placeholder property and assign this to 'data-text' property
$(this).attr('placeholder', '');
//Above stement will make placeholder text empty by assigning emty string.
.blur(callback_b)
//This statement will bind the blur event to all the elements which supports placeholder.
callback_b()
//This is a function which gets called when blur event gets fired.
//Inside callback_b() below code is written
$(this).attr('placeholder', $(this).attr('data-text'));
//This statement will take the value assigned to 'data-text' in focus event and assign it back to placeholder property.
【解决方案2】:
$('[占位符]')
jQuery 找到的任何带有属性占位符的对象
.focus(...)
当元素被聚焦时做内部代码
$(this).attr('data-text',$(this).attr('placeholder'));
此行临时存储占位符(以便您稍后重新设置)
$(this).attr('placeholder','');
这将从您的元素中清除占位符
.blur(...)
元素模糊时做内码
$(this).attr('placeholder',$(this).attr('data-text'));
此行将占位符设置为存储在临时位置的值(如上所述)
【解决方案3】:
所以基本上它所做的是当您聚焦元素时,它将占位符属性的值存储在数据文本属性中并将占位符设置为空。然后模糊它只是将占位符设置为属性中的值。它存储在 data-text 属性中,因此可以稍后检索。除了在这里像变量一样存储值之外,它没有特殊用途。
如果你想知道什么
$('[占位符]').focus(function() {
确实,基本上这意味着如果您关注任何具有占位符属性的对象,请调用该函数。
【解决方案4】:
$(function () {
'use strict';
//hide Placeholder on From Focus
$('[placeholder]')
.focus(function () {
$(this).attr('data-text', $(this).attr('placeholder'));
$(this).attr('placeholder', '');
})
.blur(function () {
$(this).attr('placeholder', $(this).attr('data-text'));
});