CSS - 如何计算总页数?

时间:2018-03-16 09:26:06

标签: html css css-print

我正在尝试显示PDF文件的页数。

所以在标题中我把这个css:

.page-number:after { 
  counter-increment: pages; 
  content: counter(page) " of " counter(pages); 
 }

HTML:

<span class="page-number">Page </span>

但它会返回Page 1 of 1 ... Page 2 of 2。 第一个计数器工作正常,但总计是错误的。 我该如何解决?

2 个答案:

答案 0 :(得分:3)

无法通过CSS计数器获得计数器总数,因此我能想到获得所需输出的唯一方法是复制HTML(如果内容是动态生成的,这可能不是一个大问题)。输出一次HTML以获得总页数然后再次获取当前页面。

&#13;
&#13;
#pageCounter {
  counter-reset: pageTotal;
}
#pageCounter span {
  counter-increment: pageTotal; 
}
#pageNumbers {
  counter-reset: currentPage;
}
#pageNumbers div:before { 
  counter-increment: currentPage; 
  content: "Page " counter(currentPage) " of "; 
}
#pageNumbers div:after { 
  content: counter(pageTotal); 
}
&#13;
<div id="pageCounter">
  <span></span>
  <span></span>
  <span></span>
  <span></span>
</div>
<div id="pageNumbers">
  <div class="page-number"></div>
  <div class="page-number"></div>
  <div class="page-number"></div>
  <div class="page-number"></div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

&#13;
&#13;
.page{
counter-reset: page;
}
.page .page-number{
  display:block;
  }
.page .page-number:after{
counter-increment: page;
content:counter(page);
}
.page:after{
    display: block;
    content: "Number of pages: " counter(page);
}
&#13;
<div class="page">
<span class="page-number">Page </span>
<span class="page-number">Page </span>
<span class="page-number">Page </span>
<span class="page-number">Page </span>
</div>
&#13;
&#13;
&#13;