页面加载时,在文本框中显示光标和文本

时间:2011-03-29 19:05:40

标签: asp.net-mvc

我正在研究Asp.net MVC。

我正在使用常规HTML

  <label for="txtbox1" > User Name</label>
<input type="text" id="txtbox1" name="text" class="water"/>

我希望在页面加载时在文本和文本之前显示Cursor。当用户在该文本框中开始写入时,“用户名”被删除。

1 个答案:

答案 0 :(得分:1)

你需要使用javascript。如果你正在使用jquery,你可以:

$(function() {
    $('#txtbox1').focus();
});

如果你想用普通的javascript做到这一点:

window.onload = function() {
    var textbox = document.getElementById('txtbox1');
    if (textbox != null) {
        textbox.focus();
    }
};

更新:

如果您希望文本在用户开始输入时消失,您可以尝试以下操作:

$('#txtbox1').keypress(function() {
    if (!$(this).data('dirty')) {
        $(this).val('').data('dirty', true);
    }
});

Live demo.