简体   繁体   English

如何激活在JavaScript中单击按钮上的文本输入

[英]How to activate text input on a button click in javascript

I am trying to activate a text input using a button. 我正在尝试使用按钮激活文本输入。 My function is like this. 我的功能是这样的。

function showHide4()
{
 document.getElementById('snack').readOnly=false;
 document.getElementById('snack').style.backgroundColor"#ffffff";   
}

This function makes text input writable and changes background to white, but it gets activated only after I click on it. 此功能使文本输入可写并将背景更改为白色,但是只有在单击它后才能激活。

Note:- My idea of activated text input is cursor(|) blinking in it. 注意:-我激活的文本输入的想法是其中的光标(|)闪烁。 maybe activated is not a correct word for it but I don't know what else to call it. 也许激活不是一个正确的词,但我不知道该怎么称呼它。

EDIT:- I tried focus(), Problem in using focus() is Default value in my text input is getting selected automatically, which is not what I want, I want to put cursor(|) after that value. 编辑:-我尝试过focus(),使用focus()的问题是我的文本输入中的默认值被自动选择,这不是我想要的,我想在该值之后放置cursor(|)。

Try this, I think focus() is what you are looking for: 试试这个,我认为focus()是您要寻找的:

function showHide4() {
    var el = document.getElementById('snack');
    el.readOnly = false;
    el.style.backgroundColor = "#ffffff";
    el.focus();
    el.value = el.value;
};

To do what you want you need to cheat a bit, just reset (set again) the value of the input and it will work as you want. 要做您想做的事情,您需要作弊,只需重置(再次设置)输入的值,它就可以根据需要工作。

DEMO HERE 此处演示

function showHide4()
{
 document.getElementById('snack').readOnly = false;
 document.getElementById('snack').style.backgroundColor = "#ffffff";  
 document.getElementById('snack').focus(); 
}

This will work! 这将起作用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM