How to highlight input text field upon clicking it

2019-06-24 14:32发布

问题:

I would like the value of the input text box to be highlighted when it gains focus, either by clicking it or tabbing to it.

<html>
<body>

<script>
function focusTest(el)
{
   el.select();
}
</script>

<input type="text" value="one" OnFocus="focusTest(this); return false;" />
<br/>
<input type="text" value="two" OnFocus="focusTest(this); return false;" />

</body>
</html>

When either input field is clicked in Firefox or IE, that field is highlighted. However, this doesn't work in Safari. (NOTE: it works when tabbing between fields.)

回答1:

I noticed Safari is actually selecting the text then removing the selection quickly.

So I tried this quick workaround that works in all browsers:

function focusTest(el)
{
  setTimeout (function () {el.select();} , 50 );
}

Edit :
Upon further testing it turns out the OnMouseUp event is clearing the selection so it is enough to add

onMouseUp="return false;"

to the input element for things to work as they should.



回答2:

Not sure about a Safari-specific solution here, but an alternative would be to wrap the input element in a div and set the border properties of it via CSS. Then change border color, etc. when focused and unfocused.