2012-12-21 46 views
1

基本上我有一個html頁面,上面有數百個圖像,每個圖像都有一個描述圖像的標題屬性。理想情況下,我會改變這一切,但頁面必須保持現在的狀態。搜索HTML img標題屬性

我想要搜索這些標題屬性,並在可能的情況下將頁面滾動到相應的圖像。 - 我已經玩過一些javascript搜索腳本,但無法直接使用「在頁面」搜索,因爲代碼是在代碼中,而不是在頁面上顯示。

任何人都可以指出我在正確的方向如何做這樣的事情嗎?

這是我使用

var n = 0; 
function findInPage(str) { 
    var txt, i, found; 
    if (str == "") { 
     return false; 
    } 
    // Find next occurance of the given string on the page, wrap around to the 
    // start of the page if necessary. 
    if (window.find) { 
     // Look for match starting at the current point. If not found, rewind 
     // back to the first match. 
     if (!window.find(str)) { 
      while (window.find(str, false, true)) { 
       n++; 
      } 
     } else { 
      n++; 
     } 
     // If not found in either direction, give message. 
     if (n == 0) { 
      alert("Not found."); 
     } 
    } else if (window.document.body.createTextRange) { 
     txt = window.document.body.createTextRange(); 
     // Find the nth match from the top of the page. 
     found = true; 
     i = 0; 
     while (found === true && i <= n) { 
      found = txt.findText(str); 
      if (found) { 
       txt.moveStart("character", 1); 
       txt.moveEnd("textedit"); 
      } 
      i += 1; 
     } 
     // If found, mark it and scroll it into view. 
     if (found) { 
      txt.moveStart("character", -1); 
      txt.findText(str); 
      txt.select(); 
      txt.scrollIntoView(); 
      n++; 
     } else { 
      // Otherwise, start over at the top of the page and find first match. 
      if (n > 0) { 
       n = 0; 
       findInPage(str); 
      } 
      // Not found anywhere, give message. else 
      alert("Not found."); 
     } 
    } 
    return false; 
} 
+1

是您的首選解決方案定製JavaScript的搜索或默認瀏覽器找到? –

+0

Javascript搜索是我的首選解決方案 – user1921990

+0

OT:使用alt屬性與標題,以便它們可以訪問。 –

回答

1

您可以通過HTML屬性選擇「搜索頁上的」代碼。

使用純JS(現代瀏覽器中含IE8 +):

document.querySelectorAll('[title*="my text"]') 

使用jQuery:

$('[title*=my text]') 

會發現:

<img src="/path" title="this is a title with my text" /> 

從那裏,你將需要獲取選擇器返回的圖像的頁面位置,然後將頁面滾動到該點,可選(有可能)使用某個偏移量所以它不會爆炸了針對視

編輯的頂部:

function findElementsByTitle(str) { 
    return document.querySelectorAll('[title*="' + str + '"]');  
} 

function scrollToElement(el) { 
    var yOffset = el.offset().top; //this is a jQuery method...you don't want to write this in plain JS 
    window.scrollTo(0, yOffset - 10) //params are x,y. the - 10 is just so your image has some "padding" in the viewport 

} 
+0

非常感謝,我會看到我如何繼續。 – user1921990

+0

權利我似乎不能在我找到的Javascript搜索代碼中實現這一點,你能建議最簡單的方法來實現它嗎? – user1921990

+0

你是什麼意思的「Javascript搜索代碼」?你能用你試過的東西來更新你的問題嗎? – BLSully