如何在 HTML 中引用 JS 变量?

How do I reference a JS var in HTML?

之前没学过JS,现在刚学CSS,偶然发现了这个动画教程,想试试。 http://goinkscape.com/how-to-animate-icons-with-inkscape-and-snap-svg/ 它没有工作:<(空白页输出)......我认为这是因为我必须提取 JS var 以便我可以输出它。我在 SO 上寻找解决方案并尝试 document.getElementById('iconDiv').innerHTML = s; 但这没有用。 感谢任何帮助。

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Inkscape Animated Icon Snap</title>
<!--We need to add the Snap.svg script to our document-->
        <script src="snap.svg-min.js"></script>
        <script>
//Run script right away
            window.onload = function () {
//We'll be appending the icon to this DIV later
                var s = Snap("#iconDiv");
//Have Snap load the SVG file
                Snap.load("icon.svg", function(f) {
//Assign the white rectangle
                    whiteRect = f.select("#whiteRect");
//Assign the whole icon group
                    icon = f.select("#icon");
//When the icon is hovered over, have the white rectangle move up slightly with elastic properties
                    icon.hover(function() {
                        whiteRect.animate({y:960}, 500, mina.elastic);
                    },
//And return to original position when not hovered over
                               function() {
                        whiteRect.animate({y:977.36218}, 500, mina.elastic);
                    }
                    );
//Finally append the icon to iconDiv in the body
                s.append(f);
                });          
            };
        </script>
    </head>
    <body>
<!--Here's the DIV that will hold the animated SVG icon-->
<div id="iconDiv"></div>        
    </body>
</html>

我回去重新做了一遍如下:

  1. 制作了一个 100x100 像素的蓝色方块。设置 ID:blueRect,标签:#blueRect。
  2. 制作了一个 50x50 像素的白色正方形。设置 ID:whiteRect,标签:#whiteRect。
  3. 将它们分组并设置ID:icon,标签:#icon。
  4. 在我的 index.html 文件所在的同一文件夹中 icon.svg 另存为 Plain SVG。
  5. 已下载 Snap.svg 并将 snap.svg-min.js 放在我的 index.html 文件所在的同一文件夹中。
  6. 在记事本中打开 icon.svg:

    "id="whiteRect" 宽度="13.229167" 高度="13.229167" x="6.6145835" y="277.15625"

我不知道为什么这些是数字(与我的第一次试验相同),因为这次我特意将我的方块放在 0,0 ...我什至保存了一个不同名称的副本。仍然得到这些数字,但无论如何...

  1. 直接从网站上复制粘贴html代码,先把y改成277.15625,再改成0。

  2. 设置另一个y为270,然后-15。

icon.hover(函数() { whiteRect.animate({y:-15}, 500, mina.elastic);

两次都是空白页。

您查看控制台了吗?您的控制台是否显示以下错误?

Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

这是由您试图通过 html 加载本地文件的行 <script src="snap.svg-min.js"></script> 引起的。如果人们可以将他们的本地文件加载到网站,那将是一个安全风险。为了解决这个问题,运行 启用了 cors(跨源资源共享)的 HTTP 服务器。这里我使用的是可以用 npm 安装的 http-server。我正在侦听端口 8000,并且 运行 从与文件相同的目录(注意句点)连接服务器。

http-server . -o --cors -p 8000

此外,在您的 index.html 中,您需要将所有对本地目录的引用更改为 http://localhost:8000/<file name here>。之后,您无需在本地打开 index.html,而是浏览至 http://127.0.0.1:8000/ 来观看动画。这对我有用,至少在 IE 上是这样。 Chrome 好像对cors比较严格,还没想好怎么过。我没试过 Firefox。