質問

I'm using the contenteditable attribute on a <div> in order to make it act as a text field on demand (for users to rename something). But I want to enable autofocus on it as well, so users can begin typing immediately (the <div> always has contenteditable enabled initially).

Is this valid and/or possible? Or will I have to switch to a standard text input?

役に立ちましたか?

解決

You'll have to do it with JavaScript in most browsers, I think. And it won't work on iOS, which only allows programmatic use of focus() in an event handler of a genuine user interaction (such as a click or touch-related event).

Also, be aware that if there other inputs on the page, it's possible the user may focus on one of those before the document has completely loaded, in which case it is then very annoying for the user to find that the focus has been moved from under them when the load event does fire, so you should use the inputs' focus events to track this.

<div contenteditable="true" id="editable"></div>

<script type="text/javascript">
    window.onload = function() {
        document.getElementById("editable").focus();
    };
</script>

他のヒント

For future viewers:

I think I may have a slightly more elegant solution.

$(window).on("load", function() {
  $("[autofocus]").focus();
});

So, once the page loads... BAM jQuery focuses on the element with the 'autofocus' attribute!

You could play around with the selector to get exactly what you want.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top