jQuery输入值焦点和模糊

Kar*_*arl 10 javascript jquery focus blur placeholder

我有以下代码,以便当用户选择一个输入框时,该值将消失,但一旦用户单击它,将重新插入默认值.

        $(function() {
            var defaultText = '';
            $('input[id=input]').focus(function() {
                defaultText = $(this).val();
                $(this).val('');
            });
            $('input[id=input]').blur(function() {
                $(this).val(defaultText); 
             });
         });
Run Code Online (Sandbox Code Playgroud)

但是,这并不是我想要的.如果用户插入文本,我不希望默认文本覆盖用户放置的内容.我也是jQuery的新手,所以任何帮助都会非常感激.

dou*_*arp 20

在你的focus()方法中你应该检查它是否等于defaultText之前清除它,并且在你的blur()函数中,你只需要val()在设置之前检查它是否为空defaultText.如果您要使用多个输入,最好使用类而不是ID,因此您的选择器将input.input在类"输入"时使用.即使它是ID,您也可以将其引用为input#input.

// run when DOM is ready()
$(document).ready(function() {
    $('input.input').on('focus', function() {
        // On first focus, check to see if we have the default text saved
        // If not, save current value to data()
        if (!$(this).data('defaultText')) $(this).data('defaultText', $(this).val());

        // check to see if the input currently equals the default before clearing it
        if ($(this).val()==$(this).data('defaultText')) $(this).val('');
    });
    $('input.input').on('blur', function() {
        // on blur, if there is no value, set the defaultText
        if ($(this).val()=='') $(this).val($(this).data('defaultText')); 
    });
});
Run Code Online (Sandbox Code Playgroud)

这个jsFiddle中设置它.