搜索HTML IMG标题属性



基本上我有一个HTML页面,上面有数百个图像,每个图像都有描述图像的标题属性。理想情况下,我会更改所有这些,但页面必须保持原样。

我想搜索这些标题属性,然后将页面滚动到相应的图像(如果可能)。 - 我已经玩过一些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;
}

您可以通过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
}

最新更新