簡體   English   中英

JavaScript中的iframe位置

[英]iframe location in javascript

在此示例中,警報為空; 我想讀取iFrame的位置,為此使用了object.src,但只有在設置其src屬性時它才起作用。 但是我使用window.open方法設置了iFrame的位置,在這種情況下,它無法正常工作。 我所做的 ?

<body>    
<iframe id="location" name="address" style="width:700px; height:700px;">  
</iframe>    
<script type="text/javascript" language="javascript">  
    window.open("http://www.google.com","address");  
    function clickMe()  
    {  
        var src = document.getElementBy Id("location").src;  
        alert(src);  
    }  
</script>  
<input type="button" onclick="clickMe()" value="click Me"/>  
</body>

除了使用window.open()之外,為什么不使用:

document.getElementById("location").src = "http://www.google.com";

現在,您可以使用getElementById()獲取其位置

您可以通過訪問location.href屬性來實現。 當然,出於安全原因,如果iframe是另一個域,瀏覽器將不允許您訪問它。

var oIframe = document.getElementById("location");
// for compatibility
var oDoc = oIframe.contentWindow || oIframe.contentDocument;
if (oDoc.document) {
    oDoc = oDoc.document;
}
alert(oDoc.location.href);

如果您通過應該在同一域中使用的句柄訪問,則存在相同的安全問題

<script>
var win;
function load(link) {
  win=window.open(link.href,link.target)
  return win?false:true;
}
function tell(winName) {  
  try {
    alert(win.location.href)
    try {
      var handle = window.open('',winName);
      alert(handle.location.href)
    }
    catch(e) {
      alert('oops getting location via window handle:'+e.message)
    }
  }
  catch(e) {
    alert('Ooops getting location:'+e.message)
  }
}  
</script>

<iframe src="about:blank" name="if1"></iframe><br/>
<a href="http://www.google.com" target="if1" onClick="return load(this)">Load foreign link</a><br />
<a href="showhref.html" target="if1" onClick="return load(this)">Load local link</a><br />
<a href="#" onClick="return tell('if1')">Tell</a><br />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM