如何激活对材料设计Web组件文本字段的关注?

时间:2018-10-29 20:48:14

标签: javascript material-design material-components material-components-web

我有这个代码

    this.mdc_text = mdc.textField.MDCTextField.attachTo(this.$el);
    if (this.autofocus) {
        this.mdc_text.activateFocus();
    }

,但是函数activateFocus尚未定义。我该如何集中精力?

https://material.io/develop/web/components/input-controls/text-field/

谢谢

1 个答案:

答案 0 :(得分:1)

为框架创建组件时,

activateFocusMDCTextFieldFoundation一起使用。在您的情况下,您似乎正在尝试以编程方式聚焦MDC文本字段,因此您只需要选择input元素(而不是div包装器)并使用focus()。 / p>

编辑:上述方法不适用于所有浏览器(即出于某种原因focus事件未在Firefox中注册)。您可以在通过activateFocus属性实例化组件之后访问foundation_方法,但是activateFocus方法仅激活MDC组件的焦点状态样式,而无需实际设置焦点,光标位置,等到input元素。该代码段已被编辑以演示。

例如:

const field = mdc.textField.MDCTextField.attachTo(document.querySelector('.mdc-text-field'));
const fieldInput = document.querySelector('.mdc-text-field__input');

// focuses in Chrome but does not register in Firefox
fieldInput.focus();

// activates MDC focus state styles across browsers but does not actually focus input, set cursor, etc
field.foundation_.activateFocus(); 
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Material TextField</title>
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700">
    <link rel="stylesheet" href="https://unpkg.com/material-components-web/dist/material-components-web.min.css">   
  </head>

  <body>
  
    <div class="mdc-text-field">
      <input type="text" id="my-text-field" class="mdc-text-field__input">
      <label class="mdc-floating-label" for="my-text-field">Hint text</label>
      <div class="mdc-line-ripple"></div>
    </div>
    
    <script src="https://unpkg.com/material-components-web/dist/material-components-web.min.js"></script>
    
  </body>
</html>

顺便说一句,如果您希望TextField自动关注页面加载,则可以将autofocus属性添加到html中的input元素中。