2011-06-22 55 views
5

屏幕旋轉後恢復HTML文檔中滾動位置的最佳方法是什麼? (這是在Cocoa Touch UIWebView中,但我認爲這是一個問題無處不在)。默認行爲似乎以像素爲單位還原y偏移量,但由於文本已被重新排列,所以現在在文檔中的位置不同。HTML/Javascript:在屏幕旋轉後修復滾動位置

我最初的想法是:

  1. 辣椒與不可見的,唯一地-id'ed元件的文檔。
  2. 旋轉之前,搜索元素e其y座標偏移量最接近滾動偏移量。
  3. 旋轉後,將滾動偏移更新爲e的新y偏移量。

即使這樣做,我寧願不插入一堆crud到文檔中。有沒有更好的辦法?


下面是解釋問題的圖表。恢復原始的y偏移不會產生預期的結果,因爲在橫向模式下更多文本適合一行。

enter image description here

回答

2

不漂亮,但它的作品。這要求在整個文檔文本中都有span標籤。

// Return the locator ID closest to this height in pixels. 
function findClosestLocator(height) { 
    var allSpans = document.getElementsByTagName("span"); 
    var closestIdx = 0; 
    var closestDistance = 999999; 
    for(var i = 0; i < allSpans.length; i++) { 
     var span = allSpans[i]; 
     var distance = Math.abs(span.offsetTop - height); 
     if(distance < closestDistance) { 
      closestIdx = i; 
      closestDistance = distance; 
     } 
    } 
    return allSpans[closestIdx].id; 
} 

旋轉之後,document.getElementById(spanId).offsetTop是新的y偏移量,其中spanIdfindClosestLocator()旋轉之前的結果。

0

概念上的問題是不是很難想到。您有滾動事件,旋轉事件和變量。我將跟蹤scroll事件中document.body DOM節點上的scrollTop位置。重新應用它與定位事件觸發。

也許這樣的事情。

// Track position 
var pos; 

// On scroll update position 
document.body.addEventListener("scroll", function() { 
    pos = document.body.scrollTop; 
}, true); 

// On rotation apply the scroll position 
window.addEventListener("orientationchange", function() { 
    document.body.scrollTop = pos; 
}, true); 
+0

我已添加圖片以闡明問題。恢復原始的y偏移不會產生預期的結果,因爲在橫向模式下更多文本適合一行。 – kvance