【问题标题】:How to Bind an CSS attribute to a Table Cell with Svelte如何使用 Svelte 将 CSS 属性绑定到表格单元格
【发布时间】:2021-11-14 19:41:21
【问题描述】:

我了解使用 Svelte(或任何其他框架)直接访问 DOM 不是一个好主意,例如。 document.getElementById 然后对它做点什么。我有一个已经作为 Svelte 组件在页面上的非动态表,然后我还有以下数据:一个表示表行单元格的数组(假设我每行有 5 个单元格)以及另一个数组,其中每个元素都有我必须在对应的表格单元格中添加 CSS 属性 active='1' 的索引号。

例如:arrIdxs = [1,3,4]arrCells = [a,b,c,d,e]

<table>
<tr>
<td>a</td>
<td active="1">b</td>
<td>c</td>
<td active="1">d</td>
<td active="1">e</td>
</tr>
</table>

有什么好的方法可以做到这一点?

【问题讨论】:

  • 我不懂你的 CSS。但是您可以为每个 td 添加一个 use 指令。类似于:use:setActive={arrIds}。 use 函数可以访问节点(dom)来更新你的 td.如果你需要更新你的 td 样式,你可以使用: Object.assign(node.style, { ... some css here ... }) in the setActive.
  • 不知道'use'指令...一定会检查的!谢谢...

标签: dom svelte svelte-component


【解决方案1】:

我不确定我是否理解用例,但您必须这样做:

<script>
    const arrIdxs = [1, 3, 4];
    const arrCells = ['a', 'b', 'c', 'd', 'e'];
</script>

<table>
    <tr>
        {#each arrCells as cell, index}
            <td class:active={arrIdxs.includes(index)}>{cell}</td>
        {/each}
    </tr>
</table>

<style>
    .active {
        background-color: red;
    }
</style>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    • 2010-09-19
    • 2021-07-01
    • 2011-07-15
    • 2019-02-28
    • 2020-04-26
    • 2015-05-19
    相关资源
    最近更新 更多