微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 聚合物1.0元素的动态类

我创建了这个组件来演示我的问题.正如预期的那样,这个组件在chrome和firefox中工作.但如果我写这个.$.wrapper.setAttribute(‘class’,’blue’);而不是这个.$.wrapper.setAttribute(‘class’,’blue style-scope poly-test’);它停止在Firefox中工作.

这是在事件处理程序中更改阴影dom元素上的类的首选方法,还是我做了一些意外正确的事情,可能
打破未来的版本?

另外,为什么我必须手动为firefox指定样式范围和我的元素名称

<link rel="import" href="../js/bower_components/polymer/polymer.html">
<dom-module id="poly-test">
  <style>
    .blue { border: 10px solid blue; }
    .red  { border: 10px solid red; }
    #wrapper { font-weight: bold; font-size: 42px; }
  </style>
  <template>
    <div id="wrapper" class="red"><content></content></div>
  </template>
</dom-module>
<script>
  polymer({
    is: 'poly-test',properties: {'blue': { type: 'Boolean',value: false }},listeners: { 'click': 'clickHandler' },clickHandler: function () {
      this.blue = !this.blue;
      if (this.blue) {
        this.$.wrapper.setAttribute('class','blue style-scope poly-test');
      } else {
        this.$.wrapper.setAttribute('class','red  style-scope poly-test');
      }
      this.updateStyles();
    }
  });
</script>

解决方法

Web组件的想法是使Web尽可能具有声明性.本着这种精神,聚合物实现动态类的方式应该是

陈述性方法:(https://www.polymer-project.org/1.0/docs/devguide/data-binding.html#native-binding)

...
<dom-module id="poly-test">
  ...
  <template>
    <!-- handle dynamic classes declaratively -->
    <div class$="{{computeClass(isBlue)}}">
      <content></content>
    </div>
  </template>
</dom-module>
<script>
  polymer({
    is: 'poly-test',properties: {
      'isBlue': { type: Boolean,value: false }
    },clickHandler: function () {
      this.isBlue = !this.isBlue;
    },computeClass: function (f) {
      return f ? "blue" : "red";
    }
  });
</script>

升级元素和将节点标记为DOM时(在我认为的阴暗行为下),框架使用样式范围,我认为我们不打算触摸它.

如果你真的希望强制处理,我建议使用polymer API的toggleClass()方法.

势在必行的方法:(http://polymer.github.io/polymer/)

...
<dom-module id="poly-test">
  ...
  <template>
    <div id="wrapper" class="red"><content></content></div>
  </template>
</dom-module>
<script>
  polymer({
    is: 'poly-test',clickHandler: function () {
      this.isBlue = !this.isBlue;
      this.toggleClass("blue",this.isBlue,this.$.wrapper);
      this.toggleClass("red",!this.isBlue,this.$.wrapper);
    }
  });
</script>

原文地址:https://www.jb51.cc/js/151215.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐