首页 > 解决方案 > Dynamically assign styles to DOM Element in Polymer 3.0

问题描述

I'm building a component in Polymer 3.0 for the first time, and I was wondering how to dynamically assign styles to a DOM element. I am building a horizontal timeline of events, and I would like to place vertical markers at every year in set range. In Vue.js, I would do something like this:

<year-marker v-for="(year, index) in years" :style="getPercentFromLeft(year)" :key="index"></year-marker>

In this setup, I would have a data structure with all the years that I want to display, and the v-for would loop through that data structure and render a markers for every year. The getPercentFromLeft function would calculate the percent from the left side of the screen that the marker should be positioned. The return value is in the format of {left: 10%}. The year-marker has additional styles, but they are specified in the style section.

What is the equivalent way to do this in Polymer 3.0? If there isn't one, what is a better way to do this?

标签: vue.jspolymerpolymer-3.x

解决方案


在 polymer3 中,您可以使用以下代码来实现。迭代您的数据结构并计算每个项目的样式。

<dom-repeat items="{{years}}"> 
    <template> 
        <paper-item class$={{getPercentFromLeft(year)}}>{{item}}</paper-item> 
    </template> 
</dom-repeat>

将为每个项目(年份)调用 getPercentFromLeft,您可以返回所需的类。


推荐阅读