CSS 网格布局更改列宽 javascript

CSS grid layout changing column width with javascript

我尝试按如下方式设置 CSS 网格布局

.wrapper {
  width: 800px;
  display: grid;
  grid-template-columns: repeat(3, 200px);
  grid-template-rows: repeat(5, 200px);
}

是否可以在 JS 中定位网格模板列然后调整列的大小?我遇到了一种情况,我可以找到它(丢失代码),但是当我尝试更改它时,Chrome DevTools 说该值是计算出来的,无法更改。

非常感谢任何指向正确方向(或其他方法,但必须使用网格)的帮助。

谢谢。

@MikeC,如果你不反对使用jQuery,你可以使用jQuery的.css()函数改变列宽,

Get the value of a computed style property for the first element in the set of matched elements or set one or more CSS properties for every matched element.

您可以在 jQuery 的函数 here 文档中阅读更多相关信息。

另外,为了让您看到实际效果,我整理了一个 codeply project,您可以看到它的实际效果。如果您单击网格上的任意位置,它将调整大小(虽然只有一次)。这是一个原始的例子。

这是它使用的 jQuery 代码。

$( "#grid" ).one( "click", function() {
  $( this ).css( "grid-template-columns", "repeat(2, 400px)" );
});

@MikeC 你没有告诉任何人你是如何让它工作的。 假设您有一个按钮或某个调用 toolExpandToggle() 的事件,并假设您的网格 CSS 定义的 class 名称称为 "canvas",那么您可以执行类似的操作。 在 CSS 我有:

@media only screen and (min-width: 768px)   {
.canvas {
    grid-gap: .0em;
    grid-template-columns: 50px auto;      /* the values are the toolbar, content */
    grid-template-rows: 50px auto 25px;     /* The values are o365Nav (O365 stardard), content, statusbar. Note: o365Nav heigth is the padding value used by the modal menu. */
    grid-template-areas:
    "o365Nav  o365Nav"
    "tool content"
    "statusbar  statusbar";
}

}

在 HTML 我有一个按钮。请注意,我将宽度定义为数据项,其中 50 与 CSS 匹配。在任何情况下,这些值将在使用时替换 CSS。

    <div class="tool" id="pl-tool" data-collasped="50"; data-expanded="200";>
    <div class="spacer"></div>
    <button class="tool-ms-button"><span class="ms-Icon ms-Icon--GlobalNavButton tool-ms-icon" aria-hidden="true" onclick="toolExpandToggle('pl-tool')"></span></button>
    <!-- now the tool bar buttons -->
    <div><button class="tool-button">item-a</button></div>
    <div><button class="tool-button">item-a</button></div>
</div>

然后我有一个javascript函数:

function toolExpandToggle(target) {
    let id = document.getElementById(target);
    let c = id.dataset.collasped;
    let e = id.dataset.expanded;

    let w = document.getElementsByClassName('tool')[0].offsetWidth;
    if(w < e) {
       document.getElementsByClassName('canvas')[0].style.gridTemplateColumns = e + 'px auto';
    }
    else {
        document.getElementsByClassName('canvas')[0].style.gridTemplateColumns = c + 'px auto';
    }

}

在我的例子中,我只有两列。 当我单击一个按钮时,我调用切换方法并将其更改为数据值。 我希望这能让其他人走得更远。