CSS - how to create circle pie canvas like this?

前端 未结 5 946
醉酒成梦
醉酒成梦 2021-01-05 20:03

I really like this element,

\"this

but how to create it? I am not sure what\'s the correct de

5条回答
  •  無奈伤痛
    2021-01-05 20:08

    Instead of using the element, I have chosen to construct the pie chart relying on CSS and JS entirely. The HTML markup is as follow:

    The CSS is as follow. The trick is to split the circle into two halves (the nested .left and .right elements). The halves will have their overflowing content hidden, and contain nested that we will manipulate with JS for rotation later. Add vendor prefixes when appropriate :)

    .pie {
        background-color: #eee;
        border-radius: 50%;
        width: 200px;
        height: 200px;
        overflow: hidden;
        position: relative;
    }
    .pie > div {
        float: left;
        width: 50%;
        height: 100%;
        position: relative;
        overflow: hidden;
    }
    .pie span {
        background-color: #4a7298;
        display: block;
        width: 100%;
        height: 100%;
    }
        .pie .left span {
            border-top-right-radius: 0;
            border-bottom-right-radius: 0;
            -webkit-transform-origin: 100% 50%;
            transform-origin: 100% 50%;
        }
        .pie .right span {
            border-top-left-radius: 0;
            border-bottom-left-radius: 0;
            -webkit-transform-origin: 0% 50%;
            transform-origin: 0% 50%;
        }
    .pie:before,
    .pie:after {
        border-radius: 50%;
        display: block;
        position: absolute;
        top: 50%;
        left: 50%;
        -webkit-transform: translateX(-50%) translateY(-50%);
        transform: translateX(-50%) translateY(-50%);
    }
        .pie:before {
            background-color: #fff;
            content: "";
            width: 75%;
            height: 75%;
            z-index: 100;
        }
        .pie:after {
            content: attr(data-percent) "%";
            z-index: 200;
            text-align: center;
        }
    

    I have used the following with jQuery:

    $(function() {
        $(".pie").each(function() {
            var percent = $(this).data("percent").slice(0,-1), // Removes '%'
                $left = $(this).find(".left span"),
                $right = $(this).find(".right span"),
                deg;
    
            if(percent<=50) {
                // Hide left
                $left.hide();
    
                // Adjust right
                deg = 180 - (percent/100*360)
                $right.css({
                    "transform": "rotateZ(-"+deg+"deg)"
                });
            } else {
                // Adjust left
                deg = 180 - ((percent-50)/100*360)
                $left.css({
                    "transform": "rotateZ(-"+deg+"deg)"
                });
            }
        });
    });
    

    Here is the fiddle: http://jsfiddle.net/Aw5Rf/7/

提交回复
热议问题