Kar*_*rdo 8 html-table bootstrap-4
我有一个带有动态行的表,我使用 bootstrap 隐藏了其中的一列hidden-xs。下一行是页脚正在使用colspan.
我想知道是否可以colspan根据`screen-size (hidden-xs)设置数量。
<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>
Run Code Online (Sandbox Code Playgroud)
更新
现在我想到了这样的方法:
<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>
Run Code Online (Sandbox Code Playgroud)
有没有更好的解决办法?
首先,Bootstrap 4 没有类hidden-xs。事实上,它没有任何类型的hidden-*实用程序。除非您自己定义了此类实用程序,否则您可能应该使用d-none d-sm-table-cell类而不是hidden-xs.
记录在这里
对于您的问题,您无法使用 CSScolspan进行响应式设置<td>。
正确的方法是使用 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)
Run Code Online (Sandbox Code Playgroud)
其中2和是当is /时4要设置的 colspan 值。您需要向要更改的每个单元格添加类。colspanisXs.matchestruefalsevariable-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>
Run Code Online (Sandbox Code Playgroud)
此处使用 JS 的优点是,您不需要交换 DOM 元素,这可能会丢失元素上绑定的事件或在较大的表上产生渲染性能问题。当然,这些问题是可以解决的,但最好一开始就不要解决。
JS 还可以轻松处理多种情况,而使用 CSS 解决方法时,您需要为每种情况使用单独的元素。
| 归档时间: |
|
| 查看次数: |
638 次 |
| 最近记录: |