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>

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...