javascript - 如何在父元素宽度为 0 时隐藏嵌套元素?

标签 javascript jquery css

我试图在嵌套的 p 标签的父级宽度为 0 时隐藏它。本质上,我希望嵌套的 p 标签在其宽度接近 0 时以及扩展时跟随父级。我敢肯定这很简单,感谢您提前提供的帮助。

Fiddle

HTML:

<div class="container">
  <div class="floater1">
    <p id="icon">X</p>
  </div>
  <div class="floater2">
    <p>This is a test</p>
  </div>  
</div>
<button>click</button>

CSS:

.container {
  width: 100%;
  height: 35px;
  border: 1px solid #000;
}
.floater1 {
  float: left;
  width: 0px;
  height: inherit;
  background: red;
  text-align: center;
  transition: width 200ms ease-in-out;
}
.show {
  width: 30px;
}
.floater2 {
  height: inherit;
  background: yellow;
  overflow: hidden;
  padding-left: 15px;
}
p {
  margin: 0;
  line-height: 35px;
}

JS:

var trigger = $('button');
var deleteBtn = $('.floater1');
trigger.click(function(){
    console.log("hello")
    deleteBtn.toggleClass('show');
})

最佳答案

你必须设置 overflow:hidden; ".floater1" 类的属性。这样当父宽度为0时p标签就会被隐藏。

var trigger = $('button');
var deleteBtn = $('.floater1');
trigger.click(function(){
	console.log("hello")
	deleteBtn.toggleClass('show');
})
.container {
  width: 100%;
  height: 35px;
  border: 1px solid #000;
}
.floater1 {
  float: left;
  width: 0px;
  height: inherit;
  background: red;
  text-align: center;
  transition: width 200ms ease-in-out;
  overflow:hidden;
}
.show {
  width: 30px;
}
.floater2 {
  height: inherit;
  background: yellow;
  overflow: hidden;
  padding-left: 15px;
}
p {
  margin: 0;
  line-height: 35px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="floater1">
    <p>X</p>
  </div>
  <div class="floater2">
    <p>This is a test</p>
  </div>  
</div>
<button>click</button>

在这里查看工作 fiddle

https://jsfiddle.net/davidsekar/7uk9n0ev/

关于javascript - 如何在父元素宽度为 0 时隐藏嵌套元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38666941/

相关文章:

javascript - 如何比较父子数据属性?

html - Internet Explorer 中的列表类型问题

css - 多列 CSS 列表绝对定位

javascript - Knockout.js:更改Observable的值不会更改html中属性的值

javascript - 我应该如何组织一个对象以尽可能地保持一切分离?

jquery - 如果未选中复选框,则使用 jquery 撤消 data-price 属性

html - CSS nth ul li 属性

.net - 如何在客户端和服务器之间重用我的 javascript 代码?

javascript - 两个 ajax 请求位于一个不存在的附加 div 中

jquery - Angular4 中的事件绑定(bind)