javascript - 如何使用 JavaScript 切换 SVG 圆圈
问题描述
我的 JavaScript 代码有问题。
单击按钮时,我想显示和隐藏两个 SVG 圆圈。
我检查控制台时似乎没有任何错误,但按钮似乎不起作用......
这是按钮的代码,我将按钮 id 设置为“strike_btn”,将 SVG 圆圈的 id 设置为“strike”
代码:
onload = function() {
function changeStr() {
var strike = document.getElementById('strike');
if (strike.style.display === 'block') {
strike.style.display = "none";
}
}
var strbutton = document.getElementById('strike_btn');
strbutton.addEventListener('click', changeStr);
}
<div class="container-fluid">
<div class="row">
<div class="col-lg-7 col-md-7 col-sm-12 col-xs-12">
<button type="button" class="btn btn-link" id="strike_btn">Strike</button>
</div>
<div class="col-lg-5 col-md-5 col-sm-8 col-xs-8">
</div>
</div>
</div>
<div class="container-fluid">
<div class="row">
<div class="col-lg-7 col-md-7 col-sm-12 col-xs-12" id="abc">
<svg width="100%" height="100%" viewBox="0 0 600 780">
<rect width="100%" height="100%" style="fill: white; stroke-width: 3; stroke: black"></rect>
<rect x="21.5%" y="24.03846154%" width="56.6666667%" height="51.92307692%" style="fill: white; stroke-width: 2; stroke: black"></rect>
<circle cx="-26.383257142857147%" cy="75.28764912669683%" r="4" fill="#1C6FA6"></circle>
<circle cx="-28.12094285714285%" cy="52.508967516968326%" id ="strike" r="4" fill="#1C6FA6"></circle>
</svg>
</div>
</div>
</div>
解决方案
您需要添加一个style
带有块的属性style="display: block;"
才能使其工作(更改了片段的 x 坐标,因为圆圈超出了窗口范围)
window.onload = function() {
function changeStr() {
var strike = document.getElementById('strike');
if (strike.style.display === 'block') {
strike.style.display = "none";
}
}
var strbutton = document.getElementById('strike_btn');
strbutton.addEventListener('click', changeStr);
};
<div class="container-fluid">
<div class="row">
<div class="col-lg-7 col-md-7 col-sm-12 col-xs-12">
<button type="button" class="btn btn-link" id="strike_btn">Strike</button>
</div>
<div class="col-lg-5 col-md-5 col-sm-8 col-xs-8">
</div>
</div>
</div>
<div class="container-fluid">
<div class="row">
<div class="col-lg-7 col-md-7 col-sm-12 col-xs-12" id="abc">
<svg width="100%" height="100%" viewBox="0 0 600 780">
<rect width="100%" height="100%" style="fill: white; stroke-width: 3; stroke: black"></rect>
<rect x="21.5%" y="24.03846154%" width="56.6666667%" height="51.92307692%" style="fill: white; stroke-width: 2; stroke: black"></rect>
<circle cx="26.383257142857147%" cy="75.28764912669683%" r="4" fill="#1C6FA6"></circle>
<circle cx="28.12094285714285%" cy="52.508967516968326%" id ="strike" r="4" fill="#1C6FA6" style="display: block;"></circle>
</svg>
</div>
</div>
</div>
推荐阅读
- bash - 我们如何对源代码文件进行部分加密/编码?
- c# - 如何在 c# 中引用特定实例?
- python - python - 如何在子图中定义 xtick 频率
- javascript - Javascript对象:将索引标题分配回该索引的分配操作?
- java - maven 项目特定脚本的最佳方法?
- python - 子类可以在 pydantic 中继承其基类根验证器吗?
- zsh - 如何配置 zsh 以完成部分单词,但不区分大小写?
- python - 为什么哈希表除了数据值之外还存储键值?
- java - 如何获取 UI 的权限名称?
- java - 无法访问类“java.lang.String”。检查您的模块类路径是否存在缺失或冲突的依赖项