【问题标题】:fixed background gradient with dynamic width具有动态宽度的固定背景渐变
【发布时间】:2016-08-11 15:15:26
【问题描述】:

我正在尝试为游戏中的士兵做 HP 条。

栏的宽度应为 50 像素,高度应为 10 像素(初始化时)。

应该是这样的:

宽度会随着血量的减少而减小。

问题是我希望背景在宽度变化时保持其渐变,例如当宽度达到 10 像素时,我只希望红色保持不变,例如:

有没有办法使用 css 做到这一点??

注意:我使用的是绝对位置,它是大父 div 的子元素。 注意 2:我对所有元素使用宽度和高度的百分比值,将这些绝对值用于 1366 宽度和 670 高度的文档。

片段:

function changeWidth()
{
    $("#hp").css("width","10%");
}

function reset()
{
  $("#hp").css("width","30%");
}
#cont {width:170px; height:170px; background:#000; position:relative}
#hp {
	position: absolute;
	bottom: 5%;
	width: 30%;
	height: 10px;
	background: linear-gradient(to left, #C7D9F8 60%, red);
	left: 5%;
	transition: all 1s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<div id="cont">
  <div id="hp"></div>
</div>

<button onclick="changeWidth()"> Run</button>
<button onclick="reset()"> Reset</button>

【问题讨论】:

  • 你能提供一个jsFiddle吗?
  • "应该是 50px 宽度和 10px 高度"..如果你在 "px" 中使用绝对测量设置宽度和高度..它不会动态调整到其父大小。这与您问题的这一部分相矛盾“问题是我希望背景随着宽度的变化保持其渐变”
  • @JuanFerreras 在这里 :) .
  • @repzero 抱歉你误会了我,值 50 px 和 10px 是我应该在 1366x670 文档上通过将百分比值放入 css 中的值。

标签: html css


【解决方案1】:

您可以在linear-gradient 背景中使用绝对值。例如,background:linear-gradient(90deg, red 10px, blue 20px); 将在元素左侧 10 像素到 20 像素之间给出从红色到蓝色的渐变,而不管元素的宽度如何。

我已将其包含在下面的小提琴中,以及您可以使用meter 标记更改条形颜色的另一种方法。

https://jsfiddle.net/jcwjptu8/

【讨论】:

    【解决方案2】:

    我采用了您的 sn-p 并将渐变上的 % 值替换为绝对像素值。我还反转了渐变,使其从左到右,从红色到另一种颜色。您可以检查,如果您修改条形的宽度,红色仍然可见。

    background: linear-gradient(to right, red, #C7D9F8 30px);

    下面是完整的sn-p:

    function changeWidth()
    {
        $("#hp").css("width","10%");
    }
    
    function reset()
    {
      $("#hp").css("width","30%");
    }
    #cont {width:170px; height:170px; background:#000; position:relative}
    #hp {
    	position: absolute;
    	bottom: 5%;
    	width: 30%;
    	height: 10px;
    	background: linear-gradient(to right, red, #C7D9F8 30px);
    	left: 5%;
    	transition: all 1s;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
    <div id="cont">
      <div id="hp"></div>
    </div>
    
    <button onclick="changeWidth()"> Run</button>
    <button onclick="reset()"> Reset</button>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-25
      • 2018-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多