如何使用CSS根据另一个元素的存在来调整元素的宽度

我的左边有一个输入框,右边有一个按钮。在某些页面上,我想在输入框旁边放置一个复选框,并将按钮移动到下方/下方。有没有办法使用 CSS flexbox 或其他东西来做到这一点?我有一个 JavaScript 条件来确定复选框是否应该出现在页面上,但不确定如何按照上述方式进行布局。


<div>

  <input type="text" />

  <!-- I would like this checkbox to be present only some of the time

  <input type = "checkbox" /> -->

  <button> click me </button>

</div>


富国沪深
浏览 233回答 3
3回答

拉丁的传说

这很简单adjacent sibling combinator,不需要 JavaScript。只需选择任何button紧邻input[type="checkbox"]并使其显示block(而不是inline)。input[type="checkbox"] + button {  display: block;}<div>  <input type="text" />  <input type = "checkbox" />  <button> click me </button></div><div>  <input type="text" />  <button> click me </button></div>

郎朗坤

您在寻找这样的东西吗?运行下面的代码片段://here we are getting each element by its idvar check = document.getElementById("check");var input = document.getElementById("input");var button = document.getElementById("button");//this is the condition we're using (it could be anything but it was easy to use a boolean for this example)var bool = false;//here is the function we're calling on clickfunction clickMe() {//when button is clicked we set bool from false to truebool = true;//if bool is true we we will apply the following styles to the check and buttonif (bool === true) {check.style.display = "inline-block";button.style.display = "block";}}#check {display: none;}<input type="checkbox" id="check"><input id="input"><button id="button" onclick="clickMe();">Click Me</button>

MM们

建议切换父级的样式function toggleClass() {&nbsp; const element = document.getElementById("container")&nbsp; element.classList.toggle("toggle");}#checkbox {&nbsp; display:none;}.toggle #checkbox {&nbsp; display:block;}<div id="container">&nbsp; <input type="text"/>&nbsp; <input id="checkbox" type="checkbox"/>&nbsp; <button onClick="toggleClass()">Button</button></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript