我有一个使用 html5 占位符的输入框:
<input type="text" name="website" class="url" required placeholder="enter website">
使用 jQuery 或直接 javascript,我想在焦点用户键入的数据前添加一个字符串。如果该字段包含的数据多于预设字符串变量(例如:http://example.com),则该字段满足我的要求。如果它仅包含原始字符串 ('http://'),则清除输入值并显示占位符。
以下代码适合我。
var input = $("#processor .url");
var prefix = 'http://';
input.focus(function() {
if (input.val().indexOf(prefix) == -1) {
input.val(prefix + input.val());
}
}).blur(function() {
if (input.val() == prefix) {
input.val('');
}
});
有没有更好的方法来写这个以提高性能等...,这是我真正的问题吗?
最佳答案
这比实际看起来要容易。 我根据@Tahir Yasin 的评论做了一个演示。
CSS:
.grey { color:#aaa; }
html:
<input type="text" />
jQuery:
var inputval = "";
$(document).ready(function() {
// Define your default value to show on input
$("input[type='text']").val("Enter your link here...");
// Add grey color or optionally blur effect
$("input[type='text']").addClass('grey');
// Save your default value
inputval = $("input[type='text']").val();
$("input[type='text']").focusin(function() {
// if textbox is empty or got the default value
if ($(this).val() == "" || $(this).val() == inputval) {
// Clear the box
$(this).val("http://"); // Your text here..
// Remove grey color
$(this).removeClass('grey'); }
}).focusout(function() {
// if textbox is empty or just contains your value
if ($(this).val() == "" || $(this).val() == "http://" ) {
// Put your Default value back
$(this).val(inputval);
// Add grey color
$(this).addClass('grey'); }
});
});
fiddle :http://jsfiddle.net/BerkerYuceer/TgZ8L/
我只是喜欢在 Action 的每一步都使用 jQuery。但是正如您所看到的,我的代码性能不如您的代码,因此您已经在使用性能最高的方法。
这是基于您的代码的演示: http://jsfiddle.net/BerkerYuceer/qbLyD/
您可以自己看到差异,它几乎相同,但显然您的代码更快。
关于javascript - jquery/javascript 将文本添加到输入字段中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13486520/