2017-10-12 73 views
3

我想增加div的宽度和高度,以便在一定的时间内,内部圆圈应该通过增加其大小来填充外部圆圈。我能够做所有事情,但只是这个职位正在引起一些问题。随着内圈的尺寸增加,其失去中心位置并向右下增加。我怎样才能不断增加它的宽度和高度,但将它保持在中心位置,这样当它完成时就完全填满了外部圆。非常感谢用Javascript增加元素的宽度和高度,同时用Javascript保留其中心位置

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>

回答

5

你只需要一个transform: translate(-50%, -50%);添加到inner圈类。这确保它正确居中。

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>

+0

感谢快速反应和一个伟大的答案,竖起大拇指d-钱 – knight

相关问题