2016-11-30 61 views
-1

我需要爲weasy print pdf構建基於html的堆疊條形圖。我已經通過將分數百分比分配給色塊圖像來完成這項工作。第三方庫不是一個選項。這對於除Safari之外我必須支持的所有瀏覽器都很適用,因爲它們可以分數百分比。因爲數據是準確的,這只是一個小小的眼睛糖果......我只是想「陪審團鑽機」而已。jQuery獲取圖像的累積高度,並根據像素偏移量調整它們的高度

  1. 我知道我的條形圖高度總是600px的
  2. 我需要我的所有圖像組合的總高度(可以說這是595px)
  3. 因爲這是百分比,我不能只是得到一個包裝height()
  4. 得到高度餘數後,我想通過遍歷每個圖像設置其高度爲height() + 1px,直到我們達到600px總數。在我的例子中,這意味着要迭代5個圖像,每個圖像添加1px。

良好的條形圖 VS. Safari的條形圖

This is an example of my working barchart enter image description here

HTML示例:

<div class="bar-container"> 
    <div class="inner-barstack"> 
     <img src="my/color-square" style="height:41.5%" alt="Bifid... 41.5%"> 
     <img src="my/color-square" style="height:39.32%" alt="Clost... 39.32%"> 
     <img src="my/color-square" style="height:0.68%" alt="Corio... 0.68%> 
     <img src="my/color-square" style="height:0.5%" alt="Veill... 0.5%"> 
     <img src="my/color-square" style="height:0.5%" alt="Enter... 0.5%"> 
     <img src="my/color-square" style="height:0.5%" alt="Bacte... 0.5%"> 
     <img src="my/color-square" style="height:17%" alt="Lacto... 17%"> 
    </div> 
</div> 

範例CSS:

.bar-container { 
    height: 600px; 
    width: 80px; 
} 
.inner-barstack { 
    height: 100%; 
    width: 100%; 
} 
.inner-barstack img { 
    width: 100%; 
} 
+2

那麼......問題在哪裏? – Dekel

+1

這是令人印象深刻的,但你有什麼反對畫布? –

+0

現在這看起來如何?因爲如果它們的高度合計爲100%,容器高度爲600px,那麼它們的高度總是應該達到600px。那麼到底發生了什麼? – aaronofleonard

回答

0

如果您需要明確地定義你的高度,你可以存儲百分比在數據屬性中並直接分配高度。

<img src="my/color-square" data-pct="41.5" alt="Bifid... 41.5%"> 

<script> 
var imgs = document.querySelectorAll('[data-pct]') 
var len = imgs.length 
var i = -1 
var t, pct 

while(++i < len){ 
    t = imgs[len] 
    pct = parseFloat(t.getAttribute('data-pct'))/100 
    t.style.height = [pct * 600, 'px'].join("") 
} 
</script> 
相關問題