2012-12-21 43 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