繁体   English   中英

CSS:如何比较自定义属性的值并根据该值申请styles?

[英]CSS: how to compare the value of a custom property and apply styles based on the value?

我正在尝试在 CSS 中构建一个状态栏。该栏显示完成/剩余的百分比,并且有这样的高端栏: |=========----------------| . 它使用两个 colors 和一个渐变来显示完成百分比。

我已将当前百分比定义为 CSS 自定义属性: --percent 通过 javascript 更改此属性会更改渐变填充,从而更新栏的显示。

高端栏的颜色基于状态栏的开始和结束 colors。

--percent达到 100% 时,我想将结束栏更改为正确的填充颜色。 CSS 中有没有一种方法可以将--percent值与“100%”进行比较,并对结束栏应用不同的样式以更改其颜色?

正如您在下面的示例中看到的,当--percent达到 100% 时,右侧的栏不会更改 colors。 我试图避免 javascript 来解决这个问题,因为如果可能的话我更喜欢 CSS 解决方案。

 // Animate the status bar. var percent = 0; setInterval(function() { $('.line').css('--percent', `${percent}%`); percent += 0.1; if (percent > 100) { percent = 0; } }, 10);
 .line { /* Customize the line with these custom properties: */ --line-thickness: 7px; --bar-height: calc(var(--line-thickness) * 4); /* --bar-height: 40px; */ --start-color: purple; --end-color: green; --percent: 0%; display: flex; justify-content: space-between; width: 50%; height: var(--line-thickness); background-color: var(--start-color); margin-top: var(--bar-height); margin-bottom: var(--bar-height); margin-left: var(--line-thickness); margin-right: var(--line-thickness); background: linear-gradient(90deg, var(--start-color) 0%, var(--start-color) var(--percent), var(--end-color) var(--percent)); }.line.left, .line.right { width: var(--line-thickness); height: var(--bar-height); margin-top: calc((var(--bar-height) - var(--line-thickness)) / -2); /* border: 1px solid white; */ }.line.left { background-color: var(--start-color); margin-left: calc(var(--line-thickness) * -1); }.line.right { background-color: var(--end-color); margin-right: calc(var(--line-thickness) * -1); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="line"> <div class="left"></div> <div class="right"></div> </div>

我会使用蒙版构建形状,任务会很容易。 为了演示,我还将 jQuery animation 替换为 CSS animation 但您可以保留它并调整background-size以控制进度

 .line { --line: 7px; --bar-height: calc(var(--line) * 4); --start-color: purple; --end-color: green; width: 50%; height: var(--bar-height); -webkit-mask: conic-gradient(at left var(--line) bottom var(--line),#0000 25%,#000 0) 0 0/calc(100% - var(--line)) calc(100% - var(--bar-height)/2 + var(--line)/2); background: linear-gradient(var(--start-color) 0 0) 0 0/0% 100% no-repeat var(--end-color); animation: fill 5s linear infinite; } @keyframes fill { to {background-size:100% 100%} }
 <div class="line"></div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM