首页 > 解决方案 > 仅使用 JavaScript(无 JQuery)检测特定“图例”元素何时在网页上可见

问题描述

我试图弄清楚如何使用 JavaScript 检测此特定元素何时出现在页面上?根据用户选择隐藏和显示多个图例元素。我无法触摸/更改网络应用程序的标记,我必须使用当前存在的内容。

        <legend>Success! We've connected to your bank. Choose an account to fund your new Bank of the West account.</legend>

我正在玩/测试从另一个网站获得的以下代码,但它不起作用(我尝试了显示/无和可见性/隐藏)。我不明白函数中的图例变量如何返回图例元素中的实际文本,但是由于这一行,应该如何生成布尔值:

var foundAndVisible = legend && (window.getComputedStyle(legend).getPropertyValue("visibility") == "hidden");
function _dtmCheckFundingPage() {
    var t = setInterval(function() {
        var legend = document.evaluate("//legend[contains(., 'Choose an account to fund your new Bank of the West account.')]", document, null, XPathResult.ANY_TYPE, null).iterateNext();
        console.log(" LEGEND HOLDS: ", legend);
        //var foundAndVisible = legend && (window.getComputedStyle(legend).getPropertyValue("display") == "none"); // of course, replace display/none by visibility/hidden 
        var foundAndVisible = legend && (window.getComputedStyle(legend).getPropertyValue("visibility") == "hidden"); // of course, replace display/none by visibility/hidden 
        console.log(" B =============== IN FUNDING PAGE CHECK - foundAndVisible holds: " + foundAndVisible);
        if (foundAndVisible) {
            clearInterval(t);
            console.log("==========found!");
        }
    }, 1000); // check every second
};

标签: javascripthtml

解决方案


我发现了这个问题。我不得不改变“foundAndVisible”的逻辑:

  var foundAndVisible = legend && (window.getComputedStyle(legend).getPropertyValue("display") == "block") && (window.getComputedStyle(legend).getPropertyValue("visibility") == "visible");

推荐阅读