You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击第一个div时调整两个div宽度的问题求助

问题原因

div元素默认不支持:focus伪类状态,所以你写的.big-width:focus相关规则根本不会被触发,这就是点击后无效果的核心原因。

解决方案

下面提供两种可行的实现方式:

方案一:通过tabindex让div可聚焦(纯CSS)

给第一个div添加tabindex属性,使其成为可聚焦元素,同时调整布局让两个div横向排列:

修改后的HTML

<div class="container">
    <div class="big-width" tabindex="0">
        <span> This div is the bigger of the two</span>
    </div>

    <div class="small-width">
        <span>This div is smaller</span>
    </div>
</div>

修改后的CSS

.container {
    display: flex;
    width: 100%;
}

.big-width{
    display:flex;
    width:100%;
    outline: none; /* 可选,移除默认聚焦边框 */
    cursor: pointer; /* 可选,提示该元素可点击 */
}

.small-width{
    display:none;
    width: 0%;
}

.big-width:focus{
    width:65%;
}

.big-width:focus ~ .small-width{
    display:flex;
    width:35%;
}

方案二:使用JavaScript切换类名(更灵活)

通过点击事件切换类名来实现效果,避免聚焦相关的额外行为:

修改后的HTML

<div class="container">
    <div class="big-width">
        <span> This div is the bigger of the two</span>
    </div>

    <div class="small-width">
        <span>This div is smaller</span>
    </div>
</div>

修改后的CSS

.container {
    display: flex;
    width: 100%;
}

.big-width{
    display:flex;
    width:100%;
    cursor: pointer;
    transition: width 0.3s; /* 可选,添加过渡动画让宽度变化更平滑 */
}

.small-width{
    display:none;
    width: 0%;
    transition: width 0.3s; /* 可选,添加过渡动画 */
}

.big-width.active{
    width:65%;
}

.big-width.active ~ .small-width{
    display:flex;
    width:35%;
}

JavaScript代码

const bigDiv = document.querySelector('.big-width');
bigDiv.addEventListener('click', function() {
    this.classList.toggle('active');
});

注:添加transition属性可以让宽度变化有平滑的过渡效果,提升用户体验,可根据需求选择是否保留。

内容的提问来源于stack exchange,提问作者DS Assignment

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 23:02:52