javascript - 如何使我的绝对定位元素响应?
问题描述
我正在尝试将这个形状圈居中(水平和垂直)在容器中间并使其具有响应性。我不知道如何在没有绝对定位的情况下保持圆形。任何帮助表示赞赏!
var n = 20;
for (var i = 0; i < n; ++i) {
var d = document.createElement('div');
var r = 360 * i / n;
var s = 'translate(200px,200px) rotate(' + r + 'deg) translate(0px, -80px)';
d.setAttribute('class', 'box');
d.setAttribute('style', '-webkit-transform:' + s);
document.getElementById("container").appendChild(d);
}
.box {
background: #d0d0d0;
width: 20px;
height: 30px;
border-radius: 7px;
position: absolute;
border: 1px solid black;
}
.box:hover {
background: red;
}
<div id='container'></div>
解决方案
将它们相对于容器定位,然后将容器居中:
var n = 20;
for (var i = 0; i < n; ++i) {
var d = document.createElement('div');
var r = 360 * i / n;
var s = 'translate(-50%,-50%) rotate(' + r + 'deg) translate(0px, -80px)';
d.setAttribute('class', 'box');
d.setAttribute('style', '-webkit-transform:' + s);
document.getElementById("container").appendChild(d);
}
#container {
position: relative;
margin:100px auto; /* 80x + 20px */
width:200px; /* 2*80px + 2*20px */
}
.box {
background: #d0d0d0;
width: 20px;
height: 30px;
border-radius: 7px;
position: absolute;
border: 1px solid black;
/* the below conmbined with the translate(-50%,-50%) in the JS will center */
top:50%;
left:50%;
}
.box:hover {
background: red;
}
<div id='container'></div>
推荐阅读
- node.js - Nginx 删除删除第二个斜线
- python - os.join() 的奇怪行为
- javascript - 为 Typescrpit 3.2 及更高版本将 .ts 文件编译为 .js
- android - 在我的 android 上发现了这个问题:AAPT: error: not well-formed (invalid token)
- php - 使用 joomla 检查 MYSQLDatabase 中是否存在记录
- python - 以不同的维度滚动数组轴(概括跨步索引滚动)
- reactjs - 在反应中是否有任何方法可以等待子组件状态并与子组件一起重新渲染父组件
- javascript - 根据 express route 中的值从 mongodb 获取数据
- python - Pandas 数据清理以分配行下方的记录被分配一个特定的值
- python - 如何在具有重复元素的排序字典中找到最小值?