简体   繁体   中英

show cursor/caret at the beginning of input box

PROBLEM : I have a html text input box with some text in it, when user click the input box, I would like to have the caret/cursor appear at the beginning of the input box.

I could move a caret by using setSelectionRange() function, but I don't like the effect that the caret shown at the end of the text input box then moved to the beginning. I would like it to be at the beginning of the input upon shown.

example: http://jsfiddle.net/edh8mkht/1/

HTML

<body>
    <input type="text" id="myP" onmousedown="mouseDown()" value="Mozilla" />
</body>

JS

function mouseDown() {
    document.getElementById("myP").style.color = "green";
    document.getElementById("myP").setSelectionRange(0,0);
}

QUESTION 1 :

I use mousedown event to move the caret, but it doesn't move the caret at all, the same thing happens if I use onfocus event. Is that because the caret appears after this two events and making setSelectionRange has no effect?

QUESTION 2:

What's a good way to solve my problem by using javascript? Note: I cannot use placeholder.

Fiddle showing initial selection of text box

Requirements for this to work:

  1. Have to be able to wrap your input in a label (or really any element which can accept a child node)
  2. Have to support pointer-events CSS property
  3. You have to be able to move the firing event from the input to the label

HTML

<label for="myP" onclick="click();">
    <input type="text" id="myP" value="Mozilla" />
</label>

CSS

input#myP {
  pointer-events: none;
}

JavaScript

function click() {
    var input = document.getElementById("myP");
    input.style.pointerEvents = 'auto';
    input.style.color = "green";
    input.setSelectionRange(0,0);
    console.log('click');
}

Important things to consider in this implementation:

  • It's essential that you protect your CSS selector with the element type. In this case, it's input#myP as opposed to #myP . Otherwise, the CSS will select both the label and the input in some browsers if the for attribute is specified.
  • You have to apply some style element to your label , otherwise this simply won't work.
  • Your caret point will always be before the initial value when clicked. At least in Chrome. That's part of the problem with your setSelectionRange call. I'd have to do some research to figure out why that is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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