html - 如何在 HTML5 进度条中显示数据标签? (跨浏览器)

标签 html css cross-browser position progress-bar

我有一个样式化的 HTML5 进度条,我想在进度条内显示跨浏览器兼容的数据标签。目前显示在进度条上方。

HTML:

<progress max="100" value="50" data-label="50% Complete"></progress>

CSS:

progress {
  text-align:center;
  height: 1.5em;
  width: 100%;
  -webkit-appearance: none;
  border: none;
}
progress:before {
  content: attr(data-label);
  font-size: 0.8em;
  vertical-align: 0
}
progress::-webkit-progress-bar {
  background-color: #c9c9c9;
}
progress::-webkit-progress-value,
progress::-moz-progress-bar {
  background-color: #7cc4ff;
}

我得到以下结果,但我想将数据标签移动到进度条内部:

current rendering

最佳答案

TL;DR:不要在 <progress> 上使用伪元素元素。

如其他答案所述,并由 me in the comments ,HTML/CSS 进度条将是比使用 <progress> 更好的解决方案。元素。

基于 Gecko 的浏览器,如 firefox,根本不会显示伪元素。

但是,要回答您的问题,只需将文本放在进度条上:

progress {
  text-align: center;
  height: 1.5em;
  width: 100%;
  -webkit-appearance: none;
  border: none;
  
  /* Set the progressbar to relative */
  position:relative;
}
progress:before {
  content: attr(data-label);
  font-size: 0.8em;
  vertical-align: 0;
  
  /*Position text over the progress bar */
  position:absolute;
  left:0;
  right:0;
}
progress::-webkit-progress-bar {
  background-color: #c9c9c9;
}
progress::-webkit-progress-value {
  background-color: #7cc4ff;
}
progress::-moz-progress-bar {
  background-color: #7cc4ff;
}
<progress max="100" value="50" data-label="50% Complete"></progress>

请注意,这有很好的浏览器支持(事实上,它非常糟糕),因为<progress>replaced element , 比如 <input> .

对于替换元素是否可以有伪元素,CSS规范并没有完全明确,所以不同的浏览器有不同的渲染。基于 Webkit 的浏览器,例如 Chrome,有时会显示它们。基于 Gecko 的,例如 Firefox,则不会。

参见 this answer关于一个有点类似的问题。

所以,如果这是一个网站,而不是 electron 应用程序或类似应用程序,我强烈建议使用 HTML/CSS 进度条:

.progress {
  height: 1.5em;
  width: 100%;
  background-color: #c9c9c9;
  position: relative;
}
.progress:before {
  content: attr(data-label);
  font-size: 0.8em;
  position: absolute;
  text-align: center;
  top: 5px;
  left: 0;
  right: 0;
}
.progress .value {
  background-color: #7cc4ff;
  display: inline-block;
  height: 100%;
}
<div class="progress" data-label="50% Complete">
  <span class="value" style="width:50%;"></span>
</div>

注意:即使这是针对带有基于 webkit 的浏览器的应用程序,您仍然不应该在 <progress> 上使用伪元素。 .正如我上面所说,此功能的规范尚不清楚,将来可能会发生变化,从而破坏您的进度元素。 Webkit 也可能会放弃对此的支持。

我建议只使用 HTML/CSS 进度条,你会在未来省去很多麻烦。

关于html - 如何在 HTML5 进度条中显示数据标签? (跨浏览器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41429906/

相关文章:

testing - Windows 8 上的浏览​​器测试?

html - 文件输入 'accept' 属性——有用吗?

html - 页脚不是 100% 底部跨浏览器

javascript 如何在任何事件上加载脚本或数据(如谷歌)而不使用ajax

html - 意识到 Chrome 中带有空 src 的 img 标签

html - CSS 导航间隙

javascript - 如何获取被点击元素的类名并使用相同的类名来操作其他元素?

javascript - HTML - 从具有透明度的 PNG 图像中实现具有自定义可点击形状的按钮

html - CSS/(文本强调 :dot) not function when applying font imported by URL

Javascript:跟随光标但停留在一个圆圈内而不是矩形 div