【问题标题】:Hide % of image's width隐藏图像宽度的 %
【发布时间】:2015-01-22 13:14:36
【问题描述】:

我有两张图片,每张都是五颗星并排的,但一张是黄色的,另一张是蓝色的。类似于以下内容(从 Google 获取):

我想将图像相互重叠,并根据用户对产品的评论分数“隐藏”顶部图像的一部分。

例如:假设图像是 50x10 像素。我将它们重叠在一起,使黄色位于蓝色之上。审查在 5/5;图像不变。审查在 4/5;只显示黄色星形图像的前 40px,剩下的 10px 显示蓝色星形(因此它会在同一图像中显示为 4 个黄色、1 个蓝色星形)。我可以只使用两张图像隐藏黄色图像的一部分,以获得 0/5 到 5/5 的完整范围。

如何使用 HTML、CSS、PHP 和/或 JS 来实现这一点?

【问题讨论】:

  • 您是否尝试过将覆盖图像放在<div> 容器内与overflow: hidden 并控制容器的宽度?
  • 您是否考虑过使用图标字体来代替?

标签: javascript php html css image


【解决方案1】:

仅使用背景图像并设置宽度。 (我刚刚使用了你的图片,但更好的图片会更容易)

.rating { 
  background-image: url(http://i.stack.imgur.com/gDqPE.png); 
  height: 100px;
  width: 100px;
}

.one-star {
    width: 115px;  
}
.one-half-star {
    width: 150px;  
}
.two-star {
    width: 190px;  
}
.two-half-star {
    width: 225px;  
}
.three-star {
    width: 265px;  
}
.three-half-star {
    width: 304px;  
}
.four-star {
    width: 340px;  
}
.four-half-star {
    width: 378px;  
}
.five-star {
    width: 414px;  
}
<div class="rating one-star"></div>
<div class="rating one-half-star"></div>

<div class="rating two-star"></div>
<div class="rating two-half-star"></div>

<div class="rating three-star"></div>
<div class="rating three-half-star"></div>

<div class="rating four-star"></div>
<div class="rating four-half-star"></div>

<div class="rating five-star"></div>

【讨论】:

  • 有没有一种方法可以将变量传递给 HTML 属性?我宁愿每个分数不要有 10 个或更多的 CSS 类,而是动态更改图像。
  • 如果图像是标准尺寸,您可以设置百分比宽度。
【解决方案2】:

在您的 CSS 中,您可以使用 CSS Clip Property 将 img 裁剪为:

.Yellow4Stars {
    position: absolute;
    clip: rect(0px,40px,10px,0px);
}

.Yellow3Stars {
    position: absolute;
    clip: rect(0px,30px,10px,0px);
}

假设满5颗星的宽度是50px,高度是10px。

【讨论】:

    【解决方案3】:

    你为什么不试试这个:

    <html>
    <head>
    <style type="text/css">
    .under
    {
    position:absolute;
    left:0px;
    top:0px;
    z-index:-1;
    }
    .over
    {
    position:absolute;
    left:40px;
    top:10px;
    z-index:-1;
    }
    </style>
    </head>
    
    <body>
    <img src="http://path-to-image" width="184" height="46" class="under" />
    <img src="http://path-to-image" width="184" height="46" class="over" />
    
    </body>
    

    调整 css 以正确定位。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-13
      • 2011-03-21
      • 2017-03-31
      • 1970-01-01
      • 1970-01-01
      • 2012-10-26
      • 2013-05-01
      相关资源
      最近更新 更多