0

我有这个 html 代码,当第二个 div 不可见时,我想让第一个 div 抓住所有宽度,这是可行的,但是我想知道它是否可以在 bootstrap 5.1 中以更优雅的方式完成:

<!DOCTYPE html>
<html>
<head>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">
</head>
<body>
    <div class=container-fluid>
        <div class="row">
            <div id="canvas" class="w-75 border">
                <p>Hi there</p>
            </div>
            <div id="submenu" class="w-25 visible">
                <p>you there</p>
            </div>
        </div>
    </div>
    <button id="button1" type="button" class="btn btn-primary">Click</button>
    <script>
        const btn = document.getElementById('button1')
        const canvas = document.getElementById('canvas')
        const subMenu = document.getElementById('submenu')
        btn.addEventListener('click', ()=>{
            console.log('I am clicked')
            if(subMenu.classList.contains('visible')){
                canvas.classList.remove('w-75')
                canvas.classList.add('w-99')
                subMenu.classList.remove('visible')
                subMenu.classList.add('invisible')
                
            } else {
                canvas.classList.remove('w-99')
                canvas.classList.add('w-75')
                subMenu.classList.remove('invisible')
                subMenu.classList.add('visible')
            }
        })
    </script>
</body>
</html>

4

1 回答 1

1

您应该使用列而不是 w-75、w-25。然后使第一列成为自动布局col,以便在隐藏另一列时它会增长以填充宽度。也使用d-none而不是可见...

<div class="container-fluid">
    <div class="row">
        <div id="canvas" class="col border">
            <p>Hi there</p>
        </div>
        <div id="submenu" class="col-3">
            <p>you there</p>
        </div>
    </div>
</div>

const btn = document.getElementById('button1')
const canvas = document.getElementById('canvas')
const subMenu = document.getElementById('submenu')
btn.addEventListener('click', () => {
    console.log('I am clicked')
    if (subMenu.classList.contains('d-none')) {
        subMenu.classList.remove('d-none')
    } else {
        subMenu.classList.add('d-none')
    }
})

https://codeply.com/p/VsC8j2BlF9

此外,使用 Bootstrap 折叠组件会更容易。那么你就不需要额外的 JavaScript 了。

https://codeply.com/p/tBb263fzdp

于 2021-08-06T10:02:49.413 回答