【问题标题】:How to control an HTML elements from inside a SVG tag如何从 SVG 标签内控制 HTML 元素
【发布时间】:2018-09-05 14:54:01
【问题描述】:

我是 .svg 文件和标签的新手。我想做一些简单的事情,但是在网上拖网 2 天后,我没有找到我真正需要的东西。请帮忙。

我有一个简单的 svg 文件,其中包含一个图像和一个圆圈(id=button)作为按钮,我想单击并控制一个 HTML 元素,在这种情况下,隐藏/显示一个 div(id=test)。 我尝试过 svg 命令和 .js,但都没有成功。 谁能帮忙?!

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"   
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> Help Me </title>
</head>

<body>
    <svg width="119" height="94" version="1.1" viewBox="0 0 119 94" 
        xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org
        /1999/xlink">

    <image width="119" height="94" preserveAspectRatio="none"  
       xlink:href="data:image/png;
       base64,iVBORw0KGgoAAAANSUhEUgAAAHcAAABeCAIAAACW+BwjAAAACXBIWXMAA
       A7EAAAOxAGVKw4bAAAA B3RJTUUH4gkFDSw6WnOjJQA............
      .............1-0.47656-1-1.059z" fill="#2b2810"/>

    <circle id="button" cx="65" cy="55" r="4" stroke="black"
       stroke-  width="3" fill="red" onclick="alert('click!')" />

  <script type="text/javascript"> 
    document.getElementById("test").hidden = true;
  </script>

</svg>

<div id="test">
   Hide/show me    Hide/show me  Hide/show me 
   Hide/show me  Hide/show me  Hide/show me 
   Hide/show me  Hide/show me  Hide/show me
</div>

</body>
</html>

【问题讨论】:

  • jsfiddle.net/ugojf6c2 你应该在做这样的事情之前学习 Javascript 基础知识。
  • 感谢您的帮助......让我走了,并进一步调查:),基本的东西,,,

标签: javascript html svg show show-hide


【解决方案1】:

知道了

<svg>..................
  <circle id="button" cx="65" cy="55" r="4" stroke="black" stroke-width="3" 
  fill="red" <button onclick="myFunction()">Try it</button> />

<script>
  function myFunction() {
  var x = document.getElementById("test");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
</script>
<svg>

【讨论】: