我有一个位于屏幕宽度 15% 处的 div。单击时,该宽度增加到 100%。它基本上是一个弹出式内容区域。
为了以良好的响应方式将原始 15% 宽度的图标居中,它们被设置为:
.parent
position: relative;
width: 15%;
.icons;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
这基本上在左侧创建了一个带有图标切换的旁边。图标在 parent
内居中。但是,当单击该图标时,我会调整父级的大小以滑出并变为 width: 100%;
。突然间,那些漂亮的百分比值相对于父级发生变化并移动到屏幕中央。我想卡住它们,让它们不动!换句话说,我希望它们保持在父 div
为 15% 时的位置。
fiddle :https://jsfiddle.net/ra6qa9jf/
最佳答案
最简单的解决方案是从红色框中删除图标 div 并为其指定一个新父级。然后将新父级的样式设置为始终具有 15% 的宽度并具有绝对位置,以便它显示为红色框上方的一层。所以你的新 HTML 可能是:
<div class="parent"></div> //This is the red box, same styling as before
<div class="parent-2"> //This is the new parent container for the icons
<div class="icons">
<i class="fa fa-plus"></i>
</div> //This is the icon, same as before
</div>
以及对应的新CSS:
.parent-2 {
position: absolute;
width: 15%;
height: 100%;
top: 0px;
left: 0px;
}
最后,您只需要更新您的 javascript,以便 onClick 监听器更改正确的 div 宽度:
(function () {
var parent = document.getElementsByClassName('parent')[0];
var icons = document.getElementsByClassName('icons')[0],
toggle = false;
icons.addEventListener('click', function(event) {
toggle = +!toggle;
if (toggle) {
parent.style.width = "100%";
} else {
parent.style.width = "15%";
}
});
}());
引用代码:
(function() {
var parent = document.getElementsByClassName('parent')[0];
var icons = document.getElementsByClassName('icons')[0],
toggle = false;
icons.addEventListener('click', function(event) {
toggle = +!toggle;
if (toggle) {
parent.style.width = "100%";
} else {
parent.style.width = "15%";
}
});
}());
.parent {
position: relative;
width: 15%;
height: 100%;
background-color: red;
transition: width 400ms ease-in-out;
}
.parent-2 {
position: absolute;
width: 15%;
height: 100%;
top: 0px;
left: 0px;
}
.icons {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: white;
font-size: 60px;
}
.icons:hover {
cursor: pointer;
}
body,
html {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<div class="parent"></div>
<div class="parent-2">
<div class="icons">
<i class="fa fa-plus"></i>
</div>
</div>
关于css - 修复(粘合)父级调整大小的 % 值的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43412018/