How to set focus on an element in Elm?

前端 未结 5 1514
暗喜
暗喜 2020-12-14 00:32

How can I set the focus on a Html element in Elm? I tried to set the autofocus attribute on the element and it only sets the focus on the page load.

5条回答
  •  长情又很酷
    2020-12-14 00:47

    A workaround for this is to use Mutation Observers. Insert this JavaScript either in your main HTML page or in the main view of your Elm code:

    var observer = new MutationObserver(function(mutations) {
      mutations.forEach(function(mutation) {
        handleAutofocus(mutation.addedNodes);
      });
    });
    var target = document.querySelector('body > div');
    var config = { childList: true, subtree: true };
    observer.observe(target, config);
    
    function handleAutofocus(nodeList) {
      for (var i = 0; i < nodeList.length; i++) {
        var node = nodeList[i];
        if (node instanceof Element && node.hasAttribute('data-autofocus')) {
          node.focus();
          break;
        } else {
          handleAutofocus(node.childNodes);
        }
      }
    }
    

    Then create HTML elements by including Html.Attributes.attribute "data-autofocus" "".

提交回复
热议问题