如何使用引导程序根据隐藏的 xs 列设置 colspan?



我有一个带有动态行的表,我使用引导hidden-xs隐藏了其中一列。作为页脚的下一行正在使用colspan

我想知道是否可以根据"屏幕尺寸(隐藏-xs)"设置colspan的数量。

<table class="table table-bordered">
{% for product in products %}
<tr>
<td class="text-left hidden-xs"><a href="{{ product.href }}">{{ product.name }}</a></td>
<td class="text-left">{{ product.model }}</td>
<td>{% for option in product.option %}
{% if option.type != 'file' %}
<div><small><span class="hidden-xs">{{ option.name }}: </span>{{ option.value }}</small></div>
{% else %}
<div><small><span class="hidden-xs">{{ option.name }}: </span><a href="{{ option.href }}">{{ option.value }}</a></small></div>
{% endif %}
{% endfor %}</td>
<td class="text-right">{{ product.quantity }}</td>
<td class="text-right">{{ product.price }}</td>
<td class="text-right">{{ product.total }}</td>
</tr>
{% endfor %}
{% for total in totals %}
<tr>
<td colspan="5" class="text-right">{{ total.title }}</td>
<td class="text-right">{{ total.text }}</td>
</tr>
{% endfor %}
<tbody>

更新
现在我想到了这种方法:

<tr class="hidden-xs">
<td colspan="5" class="text-right">{{ total.title }}</td>
<td class="text-right">{{ total.text }}</td>
</tr>
<tr class="hidden-xl hidden-lg hidden-sm">
<td colspan="4" class="text-right">{{ total.title }}</td>
<td class="text-right">{{ total.text }}</td>
</tr>

有没有更好的解决方案?

首先,Bootstrap 4 没有hidden-xs类。实际上,它没有任何类型的hidden-*实用程序。除非您自己定义了此类实用程序,否则您可能应该使用d-none d-sm-table-cell类而不是hidden-xs

记录在这里


对于您的问题,您无法使用 CSS 在<td>上设置响应式colspan

正确的方法是使用 JavaScript,如下所示:

const isXs = window.matchMedia('(max-width: 576px)')
const changeColspans = () =>
[...document.querySelectorAll('.variable-colspan')].forEach((cell) => {
cell.setAttribute('colspan', isXs.matches ? 2 : 4)
})
changeColspans()
window.addEventListener('resize', changeColspans)

其中24是您要设置为isXs.matchestrue/falsecolspan的colspan值。您需要variable-colspan类添加到要更改的每个单元格。


如果你真的想远离JS解决方案,无论出于何种原因,你可以通过为每个案例创建一个单独的<td>并使用Bootstrap的显示实用程序(上面链接)在当前响应间隔上显示适当的解决方案来解决这个问题。通用示例:

<td coslapn="2" class="d-sm-none">I render on xs only</td>
<td colspan="4" class="d-none d-sm-table-cell">I render on sm and above</td>

在这里使用 JS 的优点是不需要交换 DOM 元素,这有可能丢失绑定在元素上的事件或在较大的表上生成渲染性能问题。当然,这些问题可以解决,但最好不要首先使用它们.
JS也可以轻松处理多种情况,而使用CSS解决方法,您需要为每个情况提供一个单独的元素。

最新更新