当父级宽度为0时,如何隐藏嵌套元素

How to hide nested element when parents width is 0?

本文关键字:何隐藏 隐藏 元素 嵌套 0时      更新时间:2023-09-26

当嵌套的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');
})

您必须设置溢出:隐藏;属性设置为".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>

看到这里的工作小提琴

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

将溢出隐藏添加到.foatter1

.floater1 {
      overflow: hidden;
    }

https://jsfiddle.net/murtoza/7jusow54/1/

只需将这些添加到您的css中即可:

.floater1 p {
    opacity: 0;
    transition: opacity 250ms ease;
}
.floater1.show {
    width: 30px;
}
.show p {
    opacity: 1;
}

希望这能有所帮助!