This is a very common usecase we see on stackoverflow, facebook, etc.
You often wan开发者_如何转开发t to give the user some text to direct him on what to do, but you want the text to disappear the moment he clicks on it.
What is the easiest way to do that via JQuery? This seems like a fairly common use case
What I think you're looking for is generally called a "watermark" - and you're right, this is very common. There are a number of jQuery plugins available to do just what you're asking.
For example: http://code.google.com/p/jquery-watermark/
I use this simple script on my search input:
$(document).ready(function () {
searchInput = $('#search-input');
searchDefault = 'Please enter text';
searchInput.click(function () {
if($(this).val() == searchDefault)
$(this).val('');
});
searchInput.blur(function () {
if($(this).val() == '')
$(this).val(searchDefault);
});
});
You could also assign some other functions like changing the color or some effects to the click and blur events.
Here we go - snippet on jsfiddler.net
jQuery:
$(function() {
$('#placeholderText').val("Placeholder")
.focusin(function(){
if($(this).hasClass('initialClass'))
$(this).removeClass('initialClass').
addClass('normalClass').val('');
})
.focusout(function(){
if($(this).hasClass('normalClass') && $(this).val() == '')
$(this).removeClass('normalClass').
addClass('initialClass').val('Placeholder');
});
});
CSS:
.initialClass {
color: #999999;
}
.normalClass {
color: #000000;
}
HTML:
Click on me: <input id="placeholderText" type="text" class="initialClass" />
If the instruction text is inside the textarea you can use the toggleVal plugin. I have not used the jquery watermark plugin, it could be better so take a look at both. http://jquery.kuzemchak.net/toggleval.php
HTML:
<label for="field1">Some text to explain the text area.</label>
<textarea id="field1" name="textarea1"></textarea>
CSS:
.toggleval {
font-style: italic;
color:#333;
}
.tv-changed, .tv-focused {
font-style: normal;
color:#000;
}
Javascript:
$('.toggle').toggleVal({
populateFrom: "label",
removeLabels: true
});
In addition to all the good advice above, I find something similar to below works ok for simple sites...
$(this).focusin(function () {
}).focus(function () {
if ($(this).val() == 'Enter a comment') {
$(this).select();
}
}).val("Enter a comment").select();
});
精彩评论