How to check if IFrame is visible on page using jQ

2020-04-05 06:59发布

Suppose I have a page with multiple IFrames :

Main Page

<div id='someDiv1' style='display:none; '>
       <iframe id='iframe1' src='iframe1.html'>
           <input id='someinput'></input>
       </iframe>
</div>

IFrame (iframe1.html)

<input id='someinput'></input>
<script>
  function isElementVisible(elem){

  }
</script>

In this scenario how do i check if the element is visible/hidden due to the parent div of IFrame hiding it?

I tried using $('#someinput').is(':visible') but I always get true if I run it inside IFrame. I don't have an option to change the page structure nor execute the script inside parent.

3条回答
祖国的老花朵
2楼-- · 2020-04-05 07:33

URL parameters are your friend.

in the iframe1.html put this at the top:

<script>

    function getUrlVars() {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    }
    var test = getUrlVars();
    console.log(test[0]);

</script>

and for your main page use:

<div id='someDiv1' style='display:none; '>
    <iframe id='iframe1' src='iframe.html?visible=yes'>

    </iframe>
</div>
查看更多
混吃等死
3楼-- · 2020-04-05 07:40

The document inside your iframe is not aware of the situation in your main page... But I believe you can just 'query' your parent to check if it's visible?

$('#someDiv1', window.parent.document).is(":visible");

or without jquery because you don't really need it..

if(window.parent.document.getElementById("someDiv1").style.display != "none") 
    alert("Visible");
else 
    alert("Hidden");
查看更多
Rolldiameter
4楼-- · 2020-04-05 07:40

I am not sure if you can access the value/properties of an element within an iFrame I tried accessing the value but its gives "undefined"

Jquery try accessing value from iframe container

var isDivOpen = $("#someDiv1").is(":visible");
//for getting the state of the div : visible/hidden
查看更多
登录 后发表回答