如果父项宽度为0,如何隐藏嵌套元素?

时间:2016-07-29 20:24:40

标签: javascript jquery css

当我的父级宽度为0时,我试图隐藏嵌套的p标签。本质上,我希望嵌套的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');
})

3 个答案:

答案 0 :(得分:2)

你必须设置溢出:隐藏;属于".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/

答案 1 :(得分:0)

将隐藏的溢出添加到.floater1

.floater1 {
      overflow: hidden;
    }

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

答案 2 :(得分:0)

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

.floater1 p {
    opacity: 0;
    transition: opacity 250ms ease;
}
.floater1.show {
    width: 30px;
}
.show p {
    opacity: 1;
}
希望这可以提供帮助!