61
52

More than 5 years have passed since last update.

CSSとJavaScriptで円周上に等間隔に要素を配置する

Last updated at Posted at 2015-06-22

要素の数に合わせて円周上に等間隔に要素を配置します。

スクリーンショット 2015-06-22 22.44.08.png

HTML
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <script type='text/javascript' src='http://code.jquery.com/jquery-1.11.3.min.js'></script>
</head>
<body>
<section class="main-contents">
    <section class="circle-box">
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
    </section>
</section>
</body>
</html>
CSS
.main-contents {
    position: relative;
    width: 100%;
}
.circle-box {
    position: relative;
    margin: 0 auto;
}
div.item {
    position: absolute;
    width: 40px;
    height: 40px;
    -webkit-border-radius: 20px;
    -moz-border-radius: 20px;
    border-radius: 20px;
    background-color: #999;
}
JS
$(function(){
    var item_num = $('div.item').length;
    var deg = 360.0/item_num;
    var red = (deg*Math.PI/180.0);
    var circle_r = $("div.item").width() * 2.5;
    $('div.item').each(function(i, elem) {
        var x = Math.cos(red * i) * circle_r + circle_r;
        var y = Math.sin(red * i) * circle_r + circle_r;
        $(elem).css('left', x);
        $(elem).css('top', y);
    });
});

もっと良い書き方がありそう。

61
52
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
61
52