沿着矩形边框的进度条

问题描述 投票:0回答:2

我正在尝试弄清楚如何在矩形周围实现进度条。让我们想象一下我的 div 为 500x300,边框为 5px(黑色)。

我希望进度条从左上角开始,然后转到 -> 右上角 -> 右下角 -> 左下角 -> 然后返回起点。

Progress bar around rectangle

javascript html css css-shapes
2个回答
22
投票

纯CSS:

这种效果可以通过 CSS 使用多个线性渐变作为背景并适当定位它们来实现。做法如下:

  • 为元素的每个边框创建 4 个薄
    linear-gradient
    背景。边框的粗细决定了
    background-size
    。也就是说,如果边框厚度为 5px,则产生顶部和底部边框的线性渐变将为
    100% 5px
    (100% 宽度 5px 高度),而产生左右边框的线性渐变将为
    5px 100%
    (3px 宽度 100% 高度) ).
  • 最初设置
    background-position
    ,使得所有边框都不可见。在动画过程中,我们将每个背景渐变设置为正确的位置。这会产生动画边框的效果。

我在下面的代码片段中使用了 CSS 关键帧,因此它会自动从开始到结束进行动画(也就是说,它仅在绘制完整边框后停止),但如果您希望对其有更多控制(并说中途停止,如进度条)然后你可以使用JS并根据进度百分比修改

background-position

.progress {
  height: 300px;
  width: 500px;
  background: linear-gradient(to right, black 99.99%, transparent), linear-gradient(to bottom, black 99.99%, transparent), linear-gradient(to right, black 99.99%, transparent), linear-gradient(to bottom, black 99.99%, transparent);
  background-size: 100% 5px, 5px 100%, 100% 5px, 5px 100%;
  background-repeat: no-repeat;
  animation: progress 4s linear forwards;
  background-position: -500px 0px, 495px -300px, 500px 295px, 0px 300px;
}
@keyframes progress {
  0% {
    background-position: -500px 0px, 495px -300px, 500px 295px, 0px 300px;
  }
  25% {
    background-position: 0px 0px, 495px -300px, 500px 295px, 0px 300px;
  }
  50% {
    background-position: 0px 0px, 495px 0px, 500px 295px, 0px 300px;
  }
  75% {
    background-position: 0px 0px, 495px 0px, 0px 295px, 0px 300px;
  }
  100% {
    background-position: 0px 0px, 495px 0px, 0px 295px, 0px 0px;
  }
}
<!-- prefix free library is only to avoid browser prefixes -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>

<div class="progress"></div>


不带自动动画的CSS版本:

这是代码片段的 CSS 版本,它接受输入百分比值并据此设置边框。在文本框中提供 0 到 100 之间的值,然后单击 Enter。

window.onload = function() {
  var progress = document.querySelector('.progress'),
    totalLength = (progress.offsetWidth * 2) + (progress.offsetHeight * 2);

  var btn = document.querySelector('#enter'),
    progressVal = document.querySelector('#progress');

  btn.addEventListener('click', function() {
    input = (progressVal.value > 100) ? 100 : progressVal.value;
    borderLen = (input / 100) * totalLength;
    console.log(borderLen);
    if (borderLen <= progress.offsetWidth) {
      backgroundPos = 'background-position: ' + (-500 + borderLen) + 'px 0px, 495px -300px, 500px 295px, 0px 300px';
      progress.setAttribute('style', backgroundPos);
    } else if (borderLen <= (progress.offsetWidth + progress.offsetHeight)) {
      backgroundPos = 'background-position: 0px 0px, 495px ' + (-300 + (borderLen - progress.offsetWidth)) + 'px, 500px 295px, 0px 300px';
      progress.setAttribute('style', backgroundPos);
    } else if (borderLen <= (progress.offsetWidth * 2 + progress.offsetHeight)) {
      backgroundPos = 'background-position: 0px 0px, 495px 0px, ' + (500 - (borderLen - progress.offsetWidth - progress.offsetHeight)) + 'px 295px, 0px 300px';
      progress.setAttribute('style', backgroundPos);
    } else {
      backgroundPos = 'background-position: 0px 0px, 495px 0px, 0px 295px, 0px ' + (300 - (borderLen - (progress.offsetWidth * 2) - progress.offsetHeight)) + 'px';
      progress.setAttribute('style', backgroundPos);
    }
  });
};
.progress {
  height: 300px;
  width: 500px;
  margin-top: 20px;
  background: linear-gradient(to right, black 99.99%, transparent), linear-gradient(to bottom, black 99.99%, transparent), linear-gradient(to right, black 99.99%, transparent), linear-gradient(to bottom, black 99.99%, transparent);
  background-size: 100% 5px, 5px 100%, 100% 5px, 5px 100%;
  background-repeat: no-repeat;
  background-position: -500px 0px, 495px -300px, 500px 295px, 0px 300px;
}
<!-- prefix free library is only to avoid browser prefixes -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>
<input id='progress' type='text' />
<button id='enter'>Set Progress</button>
<div class="progress"></div>


使用 SVG:

使用 SVG,方法如下:

  • 创建单个
    path
    元素,使其形成框的边框,并使用
    getTotalLength()
    方法获取其长度。
  • 设置 stroke-dasharray
    stroke-dashoffset
    path
     属性,使路径最初不可见。
  • 通过根据进度百分比修改
    stroke-dashoffset
    ,我们可以产生类似进度条的效果。

我再次使用动画来自动触发从开始到结束的移动,但如果您想要类似进度条的效果,您可以删除动画并仅根据进度百分比设置偏移量。

window.onload = function() {
  var progress = document.querySelector('.progress path');
  var borderLen = progress.getTotalLength() + 5,
    offset = borderLen;
  progress.style.strokeDashoffset = borderLen;
  progress.style.strokeDasharray = borderLen + ',' + borderLen;
  anim = window.requestAnimationFrame(progressBar);

  function progressBar() {
    offset -= 1;
    progress.style.strokeDashoffset = offset;
    anim = window.requestAnimationFrame(progressBar);
    if (offset < 0)
      window.cancelAnimationFrame(anim);
  }
};
.progress {
  height: 300px;
  width: 500px;
}
.progress svg {
  height: 100%;
  width: 100%;
}
path {
  stroke: black;
  stroke-width: 5;
  fill: none;
}
<div class="progress">
  <svg viewBox='0 0 510 310' preserveAspectRatio='none'>
    <path d='M5,5 505,5 505,305 5,305 5,2.5' />
    <!-- end is start point - stroke width/2 -->
  </svg>
</div>


不带自动动画的SVG版本:

这是代码片段的 SVG 版本,它接受输入百分比值并根据该值设置边框。在文本框中提供 0 到 100 之间的值,然后单击 Enter。

window.onload = function() {
  var progress = document.querySelector('.progress path');
  var borderLen = progress.getTotalLength() + 5,
    offset;
  progress.style.strokeDashoffset = borderLen;
  progress.style.strokeDasharray = borderLen + ',' + borderLen;
  
  var btn = document.querySelector('#enter'),
      progressVal = document.querySelector('#progress');
    
    btn.addEventListener('click', function(){
        input = (progressVal.value > 100) ? 100 : progressVal.value;
        offsetToSet = (input/100) * borderLen;
        console.log(borderLen - offsetToSet);
        progress.style.strokeDashoffset = borderLen - offsetToSet;
    });
};
.progress {
  height: 300px;
  width: 500px;
}
.progress svg {
  height: 100%;
  width: 100%;
}
path {
  stroke: black;
  stroke-width: 5;
  fill: none;
}
<input id='progress' type='text'/>
<button id='enter'>Set Progress</button>
<div class="progress">
  <svg viewBox='0 0 510 310' preserveAspectRatio='none'>
    <path d='M5,5 505,5 505,305 5,305 5,2.5' />
    <!-- end is start point - stroke width/2 -->
  </svg>
</div>


0
投票

我为此编写了 JS Fiddle https://jsfiddle.net/killrawr/m2y1cbq0/

HTML

<div class="progress-wrapper">
    <div class="progress-border" id="progressBorder">
        <div class="progress-left"></div>
        <div class="progress-right"></div>
        <div class="progress-top"></div>
        <div class="progress-bottom"></div>
    </div>
    <div class="content" id="content">
        <p>Your content goes here</p>
    </div>
</div>

JS

function updateProgress(percent) {
    const newSquare = Square_Progress_Bar(1450);
    newSquare.updateProgress(percent);
}

function Square_Progress_Bar(amount) {
    var self = {};
    self.totalEdges = 4; // total Edges of the Box, Top | Right | Bottom | Left
    self.totalSides = 2; // Total number of sides, Top|Bottom, Left|Right
    self.totalEdgePercent = 100 / self.totalEdges; // 25%
    self.amount = Number(amount); // Any Number amount
    self.oneAmtPercent = self.amount > 0 ? (self.amount / 100) : 0; // 1% of amount
    self.amountPerSide = self.oneAmtPercent * self.totalEdgePercent; // 1% * 25 (amount per side of the square)
    self.topPercentTotal = self.totalEdgePercent * 1; // 25% of the box (1 side)
    self.rightPercentTotal = self.totalEdgePercent * 2; // 50% of the box (2 sides)
    self.bottomPercentTotal = self.totalEdgePercent * 3; // 75% of the box (3 sides)
    self.leftPercentTotal = self.totalEdgePercent * 4; // 100% of the box (4 sides)
    self.content = document.getElementById("content");
    self.contentWidth = self.content.offsetWidth; // Get content width
    self.widthPercent = (self.contentWidth / 100); // onePercent of contentWidth
    self.contentHeight = self.content.offsetHeight; // Get content height
    self.heightPercent = (self.contentHeight / 100); // onePercent of contentHeight
    self.sidesWidth = self.contentWidth * self.totalSides; // Left | Right Side
    self.sidesWidthPercent = (self.sidesWidth / 100); // onePercent of sidesWidth
    self.sidesHeight = self.contentHeight * self.totalSides; // Top | Bottom Side
    self.sideHeightPercent = (self.sidesHeight / 100); // onePercent of sidesHeight
    self.topPercent = self.totalEdgePercent; // 1 Side
    self.top = document.querySelector(".progress-top"); // Top
    self.bottom = document.querySelector(".progress-bottom"); // Bottom
    self.left = document.querySelector(".progress-left"); // Left
    self.right = document.querySelector(".progress-right"); // Right
    self.updateProgress = function(percent) {
        var that = this;
        let overall_percent = 0;
        if (percent > 100) {
            overall_percent = 100;
        } else {
            overall_percent = percent;
        }
        let max_top_width = that.heightPercent * self.topPercentTotal
        let top_percent = 0;
        let new_top_width = 0;
        let right_percent = 0;
        let new_right_height = 0;
        let bottom_percent = 0;
        let new_bottom_width = 0;
        let left_percent = 0;
        let new_left_height = 0;

        if (self.topPercentTotal > percent) {
            top_percent = ((percent / that.topPercentTotal) * 100);
        } else {
            top_percent = 100;
        }

        new_top_width = top_percent * that.widthPercent;
        new_top_width = Number(new_top_width);

        if (new_top_width >= self.contentWidth) {
            right_percent = (self.rightPercentTotal > percent)
            right_percent = right_percent ? ((percent / that.rightPercentTotal) * 100) : 100;
            right_percent = right_percent > 100 ? 100 : right_percent;
        } else {
            right_percent = 0;
        }

        new_right_height = right_percent * that.heightPercent;
        new_right_height = Number(new_right_height);

        if (new_right_height >= self.contentHeight) {
            bottom_percent = (self.bottomPercentTotal > percent);
            bottom_percent = bottom_percent ? ((percent / that.bottomPercentTotal) * 100) : 100;
            bottom_percent = bottom_percent > 100 ? 100 : bottom_percent;
        } else {
            bottom_percent = 0;
        }

        new_bottom_width = bottom_percent * that.widthPercent;
        new_bottom_width = Number(new_bottom_width);

        if (new_bottom_width >= self.contentWidth) {
            left_percent = (self.leftPercentTotal > percent);
            left_percent = left_percent ? ((percent / that.leftPercentTotal) * 100) : 100;
            left_percent = left_percent > 100 ? 100 : left_percent;
        } else {
            left_percent = 0;
        }

        new_left_height = left_percent * self.heightPercent;
        new_left_height = Number(new_left_height);

        // Set top and bottom width (horizontal progress)
        self.top.style.width = new_top_width + "px";
        self.bottom.style.width = new_bottom_width + "px";
        self.left.style.height = new_left_height + "px";
        self.right.style.height = new_right_height + "px";

    };
    return self;
};

CSS

.progress-wrapper {
    position: relative;
    display: inline-block;
}

.progress-border {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    pointer-events: none;
}

.progress-border div {
    position: absolute;
    background-color: #4caf50;
    transition: width 0.5s, height 0.5s;
}

.progress-left,
.progress-right {
    width: 3px;
    height: 0;
}

.progress-top,
.progress-bottom {
    height: 3px;
    width: 0;
}

.progress-left {
    left: 0;
    bottom: 0;
}

.progress-right {
    right: 0;
    top: 0;
    bottom: 0;
}

.progress-top {
    top: 0;
    left: 0;
    right: 0;
}

.progress-bottom {
    bottom: 0;
    right: 0;
}

.content {
    padding: 20px;
    border: 3px solid transparent;
    /* Ensures proper spacing for the border */
}
© www.soinside.com 2019 - 2024. All rights reserved.