我想设置一个固定的 div,其中包含一个图标,当它悬停在其上时会从右向左扩展( div展开,而不是图标),在左侧显示一段文字的图标.图标的位置保持不变.这是一个草图,以帮助说明我想做的
更改< div>的大小在悬停上没有问题,我只需添加一个宽度更大的类(包括转换动画扩展).但我对元素的定位感到困惑.我将图标和文本(在< span>内)放在单独的< div>中并尝试使用flex安排一切.在展开/悬停状态下,事情看起来应该是这样,但是一旦< div>再次缩小,包含图标和文本的两个div尝试共享剩下的小空间,因此图标被切断,文本被压扁.
如果有人能帮助我弄清楚如何按照我希望的方式设置它,我将不胜感激.
这是我到目前为止所获得的jsFiddle:Button-GrowOnHover
加上代码本身:
$(document).ready(function() { var button = $("#myButton"); button.mouseenter(function() { $(this).addClass("grow"); }); button.mouseleave(function() { $(this).removeClass("grow"); }); });
.button-container { position: fixed; top: 5%; right: 5%; width: 100px; padding: 5px; background-color: tomato; display: flex; justify-content: space-between; overflow: hidden; transition: width 1s; } .button-container.grow { width: 300px } .button-text-container { display: flex; align-items: center; justify-content: center; background-color: lightblue; } .button-icon-container { height: 100%; display: flex; align-items: center; justify-content: center; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="button-container" id="myButton"> <div class="button-text-container"> <span>Here comes some text.</span> </div> <div class="button-icon-container"> <img src="http://img.558idc.com/uploadfile/allimg/210615/1T1525L2-1.jpg"> </div> </div>如果您依赖flexbox order,则只能使用CSS执行此操作,并且可以将宽度更改移动到文本而不是父容器:
.button-container { position: fixed; top: 5%; right: 5%; padding: 5px; background-color: tomato; display: flex; justify-content: space-between; overflow: hidden; } .button-text-container { order:-1; display: flex; align-items: center; justify-content: center; background-color: lightblue; white-space:nowrap; /*Keep text always one line*/ overflow:hidden; width:0; transition: width 1s; } .button-icon-container { height: 100%; display: flex; align-items: center; justify-content: center; } .button-icon-container:hover + .button-text-container { width:200px; }
<div class="button-container" id="myButton"> <div class="button-icon-container"> <img src="http://img.558idc.com/uploadfile/allimg/210615/1T1525L2-1.jpg"> </div> <div class="button-text-container"> <span>Here comes some text.</span> </div> </div>