LoginSignup
15
12

More than 5 years have passed since last update.

Material Design Liteが動作しない場合の対処

Last updated at Posted at 2015-12-16

現象

動的に追加した要素に対して、Material Design Liteが正しく反映されない
(厳密には、material.min.js読み込み後に追加された要素に対して反映されない)

適当なファイルに以下のテキストを保存して開いてみると、HTMLに直接記述されているText Fieldはきちんと動くが、onloadの後にjavascriptで追加されているText Fieldは動作していないことが確認できる

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href="https://storage.googleapis.com/code.getmdl.io/1.0.6/material.indigo-pink.min.css">
    <script src="https://storage.googleapis.com/code.getmdl.io/1.0.6/material.min.js"></script>
    <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
  </head>
  <body>
    <!-- 正常に動作するMaterial Design Lite要素 -->
    <div class="mdl-textfield mdl-js-textfield">
      <input class="mdl-textfield__input" type="text" id="sample1">
      <label class="mdl-textfield__label" for="sample1">Valid Text Field...</label>
    </div>

    <!-- 正常に動作しないMaterial Design Lite要素 -->
    <div id='invalid-textfield-container'></div>
  </body>

  <!-- JavascriptでMaterial Design Lite要素を追加 -->
  <script type="text/javascript">
    $(window).load(function() {
      $('#invalid-textfield-container').html('\
          <div class="mdl-textfield mdl-js-textfield">\n\
            <input class="mdl-textfield__input" type="text" id="sample1">\n\
            <label class="mdl-textfield__label" for="sample1">Invalid Text Field...</label>\n\
          </div>\n\
          ');
    });
  </script>
</html>

原因

material.min.js読み込み時に、各Material Design Lite要素に対して初期化処理を行っているが、読み込み後に追加されたComponentに対しては行われないため

対策

要素追加後にcomponentHandler.upgradeDom()componentHandler.upgradeElement()を呼び出して初期化処理を行う

15
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
12