jQuery将光标移动到文本输入的末尾

时间:2011-09-01 08:40:38

标签: javascript jquery input textinput

目前我有一个输入框,其值为“当前网站”

当他们点击它时我运行这个功能:

function clearMeHttp(formfield) {
    if (formfield.defaultValue == formfield.value) {
        formfield.value = "http://";
    }
};

如果你点击框中它可以正常工作,但是如果你勾选到框中它只是突出显示单词“http://”,这会破坏它的目的,除非它们按下我想要避免的右箭头键。

谢谢!

以下是其他代码:<input onblur="restoreMe(this)" onfocus="clearMeHttp(this)" type="text" class="fade" name="website" value="Current website">

restoreMe只是用jquery轻轻地淡化默认值

3 个答案:

答案 0 :(得分:4)

我稍微改变了你的代码,但是使用了jquery事件而不是内联html。

使用完整脚本:

var defaultVal = 'Current website';
$(function() {

    $('.urlCheck').focus(function(e) {
        if ($(this).val() == "http://" || $(this).val() == '' || $(this).val() == defaultVal) {
            $(this).val('http://');
            $(this).select(false);

        }
    });

    $('.urlCheck').keyup(function(e) {
        if ($(this).val() == "http://" || $(this).val() == '' || $(this).val() == defaultVal) {
            $(this).val('http://');
        }
    });

    $('.urlCheck').blur(function(e) {
        $(this).val(defaultVal);
    });

});

工作链接:http://jsfiddle.net/29gks/6/

keyup 事件是Chrome和Safari的覆盖

答案 1 :(得分:0)

你没有使用jquery所以我跟着你。

脚本:

function clearMeHttp(formfield) {
    if (formfield.defaultValue == formfield.value) { 
         formfield.value="";        
         formfield.style.padding="0 0 0 40";
         document.getElementById("http").style.display="block";
    }
}; 

HTML:

<label id="http" style="float:left;position:absolute;display:none;">http://</label>
<input onblur="restoreMe(this)" onfocus="clearMeHttp(this)" type="text" class="fade" name="website" value="Current website">

符合您的要求但可能不是您想要的方式

答案 2 :(得分:0)

您需要在大多数浏览器上使用setSelectionRange()(或selectionStartselectionEnd),并在IE上使用TextRange个恶作剧。 9。

以下是我之前对同一问题的回答:How to place cursor at end of text in textarea when tabbed into

相关问题