2015-04-24 96 views
4

我有一個通過對象標籤嵌入的SVG圖形。如何獲得對象標籤的ParentElement?

<!DOCTYPE html> 
<html> 
<head> 
    <title>myTitle</title> 
    <script type="text/javascript" src="script.js"></script> 
    <link href="box.css" rel="stylesheet" type="text/css" media="screen" /> 
</head> 

<body> 
<div id ="objectcontainer"> 
    <div id="displaybox" style="display: none;"></div> 
    <object id = "mainSVG" type="image/svg+xml" data="map_complete.svg"> 
    <img id="svgPic" src="map_complete.svg" alt="Browser fail"/> 
    </object> 
</div> 
</body> 
</html> 

在SVG是鏈接:

<a id="emerBtn" xlink:href="emergency.html" onmouseover="return playVideo()" target="_parent"> 

在事件鼠標應觸發以下:

function playVideo(){ 
    //not working, all the time null 
    var doc = document.parentNode; 
    var elem = document.parentElement; 
    var otherElem = document.documentElement.parentElement; 
    //working if triggered from index.html 
    var thediv = document.getElementById('displaybox'); 
    if(wasViewed == false) //show only one time 
    { 
     if(thediv.style.display == "none"){ 
      wasViewed = true; 
      thediv.style.display = ""; 
      thediv.innerHTML = "<div id='videocontainer'><video autoplay controls style='display:block; margin-left:auto;" + 
           "margin-right:auto; margin-top:150px; margin-bottom:auto; width:600px'>" + 
           "<source src='video.mp4' type='video/mp4'>HMTL5-Video not supported!</video>" + 
           "</div><a href='#' onclick='return palyVideo();'>CLOSE WINDOW</a>"; 
     }else{ 
      thediv.style.display = "none"; 
      thediv.innerHTML = ''; 
     } 
    } //close anyhow 
    else{ 
      thediv.style.display = "none"; 
      thediv.innerHTML = ''; 
     } 
    return false; 
} 

我的問題是,我不能訪問 「顯示框」 svg。 我試過.parentNode,.parentElement,document.documentElement.parentElement等 但是所有的時候,父元素/節點都是空的。

有誰知道如何從object/svg訪問「外部」HTML元素?

回答

0

object中的SVG創建nested browsing context

要訪問該子文檔之外的元素,你需要訪問父文檔:

function playVideo() { 
    // ... 
    var parentDoc = window.parent.document; 
    var displayBox = parentDoc.getElementById('displaybox'); 
    // ... 
} 
+0

不工作對我來說,它提供了:「未捕獲的SecurityError:阻止原產框架‘訪問空’一個起源爲「null」的框架,協議,域和端口必須匹配。「 –

+1

在使用「離線」模式時,似乎有些文件存在問題。 我剛剛將svg內容直接複製到index.html中,現在它可以工作。謝謝。 –

+0

很高興它的工作。它也適用於從同一本地Web服務器運行HTML文件和SVG文件。 – joews