简体   繁体   English

从 svg 的外部 JS 脚本中获取其他 html 元素

[英]Getting other html elements from svg's external JS script

I have an svg image which I add in my .html document using <object> tags this:我有一个 svg 图像,我使用<object>将其添加到我的.html文档中:

<object data="./svg/bookmark.svg" type="image/svg+xml" id="bookmark"></object>

I can then position the svg in .css file like this:然后我可以像这样在.css文件中 position svg :

#bookmark{
            position: absolute;
            top: 0rem;
            left: calc(30rem - 0.1rem);
            z-index: 10;
            width: 1.25rem;
            height: auto;
}

So styling is working.所以造型很有效。

This svg should reveal a menu which slides from the left when svg is pressed.当按下 svg 时,这个 svg 应该会显示一个从左侧滑动的菜单。 I tried implementing JS like this:我尝试像这样实现 JS:

  1. I modified an svg:我修改了一个 svg:

    • I enabled sourcing to external JS by adding this attribute inside the <svg> tag.:我通过在<svg>标记内添加此属性来启用外部 JS 的采购。:

       xmlns:xlink="http://www.w3.org/1999/xlink"
    • I inserted a link to the external JS after the <svg> tag:我在<svg>标签之后插入了一个指向外部 JS 的链接:

       <script xlink:href="../js/bookmark.js" />
    • I added an onclick insid the <path> tag:我在<path>标签中添加了一个onclick

       onclick="bookmark_click()"
  2. I created an external JS file ../js/bookmark.js with the folowing content:我创建了一个外部 JS 文件../js/bookmark.js ,其内容如下:

     function bookmark_click(){ console.log("Bookmark clicked."); let x = document.getElementById("menu"); console.log(x); }

And I got this output in the browser's console:我在浏览器的控制台中得到了这个 output:

在此处输入图像描述

It looks like external JS script can execute simple JS commands, but fails to see other elements in my webpage - we can see that x is returned as null .看起来外部 JS 脚本可以执行简单的 JS 命令,但无法在我的网页中看到其他元素 - 我们可以看到x返回为null What am I doing wrong?我究竟做错了什么? I don't want to embed svg directly in my .html document.我不想将 svg 直接嵌入到我的.html文档中。

If the element with id="menu" is in the SVG's parent HTML document then you can use parent to get it ie如果 id="menu" 的元素在 SVG 的父 HTML 文档中,那么您可以使用 parent 来获取它,即

let x = parent.document.getElementById("menu") 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM