【问题标题】:Polymer add class when property is true当属性为真时聚合物添加类
【发布时间】:2017-02-11 13:43:28
【问题描述】:

我以前在 Angular 中看到过这种情况,想知道这是否也适用于聚合物。 Angular - What is the best way to conditionally apply a class?

我设置了一个名为“动画”的属性:

animated: {
  type: Boolean,
  value: false,
},

当动画为真时,我的元素内的 div 应该有一个 .animate 的 css 类。

<div class=""></div>

现在我已经在 ready 函数中完成了。 但自从我遇到 Stackoverflow 的问题后,我想知道这在聚合物中是否可行。

谢谢!

【问题讨论】:

    标签: polymer


    【解决方案1】:

    一种方法是使用如下函数:

    <div class$="{{_getClass(animated)}}"></div>
    

    其中class$$ 符号向Polymer 表明该属性是使用数据绑定生成的。因此,您的 _getClass 函数将如下所示:

    _getClass: function(animated){
       return animated ? "animate" : "";
    }
    

    animate 属性发生变化时,_getClass 函数将被调用,该函数将返回指示您需要的类的字符串。

    【讨论】:

      【解决方案2】:

      也可以使用PolymertoggleClass方法

      <base href="https://polygit.org/components/">
      <script src="webcomponentsjs/webcomponents-lite.min.js"></script>
      <link rel="import" href="polymer/polymer.html">
      <dom-module id="my-element">
        <template>
          <style>
            .show {
              display: block !important;
              border: 1px solid black;
            }
            .hide {
              width: 100px;
              height: 100px;
              display: none;
            }
          </style>
          <div class="hide" id="toggle"></div>
          <button on-tap="_toggleDiv">Press to toggle</button>
        </template>
      </dom-module>
      <script>
        Polymer({
          is: 'my-element',
          properties: {
            show: {
              type: Boolean,
              value: false
            }
          },
          _toggleDiv: function() {
            this.show = !this.show;
            this.toggleClass('show', this.show, this.$.toggle);
          }
        });
      </script>
      
      <my-element></my-element>

      【讨论】:

      • Uncaught TypeError: this.toggleClass is not a function
      • @Metagrapher 聚合物版本?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-21
      • 1970-01-01
      相关资源
      最近更新 更多