我正在尝试增加 div 的宽度和高度,以便在一定时间内内圈应该通过增加其大小来填满外圈。我什么都能做,只是位置有点问题。随着内圈尺寸的增加,它失去了中心位置并向右下角增加。我怎样才能继续增加它的宽度和高度,但将它保持在中心,这样当它完成时它就会完全填满外圈。非常感谢
var outer, inner, width, interval, height;
inner = document.querySelector(".inner");
width = 0;
height = 0;
window.addEventListener("load", function () {
interval = setInterval(function () {
if (width >= 200 && height >= 200) {
inner.textContent = "100% Completed";
clearInterval(interval);
}
else {
width += 3.333;
height += 3.333;
inner.style.width = width + "px";
inner.style.height = height + "px";
}
}, 1000);
});
.outer {
width: 200px;
height: 200px;
border: 5px solid tomato;
border-radius: 50%;
margin: 100px auto;
position: relative;
}
.inner {
width: 0;
height: 0;
background-color: tomato;
position: absolute;
top: 50%;
left: 50%;
border-radius: 50%;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="outer">
<div class="inner"></div>
</div>
</body>
</html>
最佳答案
你只需要添加一个transform: translate(-50%, -50%);
到inner
circle类。这确保它正确居中。
var outer, inner, width, interval, height;
inner = document.querySelector(".inner");
width = 0;
height = 0;
window.addEventListener("load", function(){
interval = setInterval(function(){
if ( width >= 200 && height >= 200 ) {
inner.textContent = "100% Completed";
clearInterval(interval);
}
else {
width += 3.333;
height += 3.333;
inner.style.width = width + "px";
inner.style.height = height + "px";
}
},500);
});
.outer {
width: 200px;
height: 200px;
border: 5px solid tomato;
border-radius: 50%;
margin: 100px auto;
position: relative;
}
.inner {
width: 0;
height: 0;
background-color: tomato;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
border-radius: 50%;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="outer">
<div class="inner"></div>
</div>
</body>
</html>
关于javascript - 使用 Javascript 暂时增加元素的宽度和高度,同时保持其居中位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46717270/