更改代码以在javascript中选择更多类

时间:2016-06-23 08:37:03

标签: javascript

看看这段代码:

<script src="progressbar.js"></script>

<script>
var bar = new ProgressBar.Line(containera, {
  strokeWidth: 4,
  easing: 'easeInOut',
  duration: 1400,
  color: '#FFEA82',
  trailColor: '#eee',
  trailWidth: 1,
  svgStyle: {width: '100%', height: '100%'},
  text: {
    style: {
      // Text color.
      // Default: same as stroke color (options.color)
      color: '#999',
      position: 'absolute',
      right: '0',
      top: '30px',
      padding: 0,
      margin: 0,
      transform: null
    },
    autoStyleContainer: false
  },
  from: {color: '#FFEA82'},
  to: {color: '#ED6A5A'},
  step: (state, bar) => {
    bar.setText(Math.round(bar.value() * 40));
  }
});

bar.animate(1.0); 
</script>

上面的代码选择带有“containera”类的元素并用它们做一些事情。我想改变我的代码,所以它也会选择下面的类: containerb,containerc,containerd,containere,containerf 但是我不想为每节课重复我的代码。我希望你帮助我:)谢谢你。

1 个答案:

答案 0 :(得分:0)

为什么不将配置包装在一个函数中并为每个容器调用它?可以这样做:

var yourContainers = ['containerA','containerB']

function createProgressbars = function(container){
 return new ProgressBar.Line(container, {
  strokeWidth: 4,
  easing: 'easeInOut',
  duration: 1400,
  color: '#FFEA82',
  trailColor: '#eee',
  trailWidth: 1,
  svgStyle: {width: '100%', height: '100%'},
  text: {
    style: {
      // Text color.
      // Default: same as stroke color (options.color)
      color: '#999',
      position: 'absolute',
      right: '0',
      top: '30px',
      padding: 0,
      margin: 0,
      transform: null
    },
    autoStyleContainer: false
  },
  from: {color: '#FFEA82'},
  to: {color: '#ED6A5A'},
  step: (state, bar) => {
    bar.setText(Math.round(bar.value() * 40));
  }
});
}

yourContainers.forEach(function(container){
  createProgressbars(container).animate(1.0);
});