【发布时间】:2018-10-20 18:20:40
【问题描述】:
我正在构建一个网页,其中包含一个显示交易的表格。
表格有一个下拉菜单,用于选择要显示的交易类型。单行表包含此下拉菜单,需要对齐以显示在事务表的右边缘。根据事务类型,还存在其他过滤器字段,这些字段从表的单行左侧开始。
根据事务类型,表格的宽度会发生变化。
我在我的视图模型中创建了一个可观察的字段,它等于表格的当前宽度。
以下标记定义了这种布局,只有一个过滤器 - 交易类型的下拉选择。
<fieldset id="transactionFilters">
<table data-bind="width: TransactionGridWidth">
<!-- I also tried the following:
<table data-bind="style: {width: TransactionGridWidth}">
I tried appending "px" to the width field as well, with no change.
-->
<tr>
<th style="width: 350px">
<div class="dropdown" style="margin: 10px 0 10px 15px">
<div align="right">
<span style="padding: 10px">View </span>
<button class="btn btn-default btn-sm dropdown-toggle" type="button" data-toggle="dropdown" aria-expanded="true">
<span id="dropdownTitle" >Type 1</span>
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Type 1</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Type 2</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Type 3</a></li>
</ul>
</div>
</div>
</th>
</tr>
</table>
</fieldset>
将一次显示以下网格之一,每个网格具有不同的宽度:
<div id="type1TransactionsGrid" style="width: 1000px;"></div>
<div id="type2TransactionsGrid" style="width: 800px; display: none;"></div>
<div id="type3TransactionsGrid" style="width: 1200px; display: none;"></div>
以下 KnockoutJS 脚本定义了 observable:
var ViewModel = {
Type1TransactionsGrid: ko.observable(),
Type2TransactionsGrid: ko.observable(),
Type3TransactionsGrid: ko.observable(),
TransactionGridWidth: ko.observable(),
OnLoad: function () {
ViewModel.TransactionGridWidth(1000);//initialisation
}
};
...//rest of the implementation
ko.applyBindings(ViewModel);
ViewModel.OnLoad();
我有一个 switch-case 来选择要显示的事务网格,并将 TransactionGridWidth 设置为当前网格宽度,如下所示:
ViewModel.TransactionGridWidth(document.getElementById('Type1TransactionsGrid')).getBoundingClientRect().width);
我确信这是可行的,因为我在屏幕上显示了字段的值,并且它会跟踪更改。调试器确认 observable 持有正确的事务网格宽度。
无论我做什么,我都无法让表格的宽度随着可观察值的变化而变化。如果我输入明确的大小,它会起作用,例如
<table width="1000px">
TLDR: 我有一个可观察变量,它成功跟踪当前显示的事务网格的宽度,但是将此变量数据绑定到我的过滤表样式不起作用。
我做错了什么?
【问题讨论】:
-
当您尝试将
px附加到您的值时会发生什么? -
我试过了 - 没有改变。将编辑我的问题以显示这一点。
-
有时我发现样式绑定不起作用并回退到 attr ---- attr: { style: 'width: '+ somevalue + 'px' },可能会完成工作如果您想要有效的答案,请使用 jsfiddle 之类的示例。
-
另外值得注意的是,如果内容需要,表格元素的宽度会推到容器的 100%。
-
你不是打算在这 3 个 div 元素上使用数据绑定而不是固定宽度吗?
标签: javascript html knockout.js observable