将光标放在焦点输入中值文本的开头 [英] Getting cursor at start of value text in input on focus

查看:68
本文介绍了将光标放在焦点输入中值文本的开头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我正在尝试实现一小段代码,其中当用户单击我的搜索输入时,文本光标会自动转到值文本的开头.值文本为搜索我们的网站...".

按下按键时,需要清除值文本,但是如果用户删除所有文本,则值文本需要重新出现...

问候,
Tom.

Hi everyone,

I''m trying to implement a small piece of code in which when the user clicks into my search input, the text cursor automatically goes to the start of the value text. The value text is "Search Our Site...".

On key down, the value text needs to be cleared, but if the user deletes all of their text, the value text needs to reappear...

Regards,
Tom.

推荐答案

了解有关 setselectionrange的信息 [^ ] .

这是您的功能:

read about setselectionrange[^].

here is your function:

function SetCursorPos (obj, pos) 
{
        obj.setSelectionRange(pos,pos);//index started from 0
}


在上面我的评论中,这里有一些代码演示了可能的解决方案.
在Chrome中进行了测试.

Further to my comment above, here''s some code that demonstrates a possible solution.
Tested in Chrome.

<!DOCTYPE html>
<html>
<head>
<style>
#searchHint
{
    z-index: -1;
    position: absolute;
}
#searchBox
{
    /* border: none; */
    background-color: rgba(0,0,0,0);
}
</style>

<script>
function byId(e){return document.getElementById(e);}
function myInit()
{
    var src = byId('searchBox');
    var x,y,w,h;

    w = src.clientWidth;
    h = src.clientHeight;

    x = src.offsetLeft;
    y = src.offsetTop;

    var tgt = byId('searchHint');
    tgt.style.left = x + 'px';
    tgt.style.top = y + 'px';

    tgt.style.width = w + 'px';
    tgt.style.height = h + 'px';
}

function checkValue(element, tgtIdStr)
{
    var src, tgt=byId(tgtIdStr);

    src = element;
    if (src.value == '')
        tgt.style.display = '';
    else
        tgt.style.display = 'none';
}
</script>

</head>
<body onload='myInit();'>
    <input id='searchBox' onkeyup='checkValue(this, "searchHint");'/>
    <div id='searchHint'>Enter Search</div>
</body>
</html>


这篇关于将光标放在焦点输入中值文本的开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆