如何根据API数据修改SVG中<rect>元素状态并添加叉号标记
解决方案
需求回顾
- SVG内
table_number类的<rect>默认fill: red、opacity: 0 - 调用API返回JSON数据,当数据中
url与SVG里<a>标签的xlink:href匹配,且status为false时:- 可选1:将对应
<rect>的opacity设为1 - 可选2:用叉号替代红色填充标记该区域
- 可选1:将对应
完整代码实现
补全API数据解析逻辑,同时提供两种标记方案:
<style> .table_number { fill: red; opacity: 0; } /* 叉号样式 */ .table-cross { stroke: #ff0000; stroke-width: 3; fill: none; } </style> <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 540 159"> <image width="540" height="159" xlink:href="https://cdn.shopify.com/s/files/1/0573/4478/6617/files/tables_number.png"></image> <a xlink:href="https://www.store.com/products/link1"> <rect class="table_number" x="46" y="54" width="86" height="70"></rect> </a> <a xlink:href="https://www.store.com/products/link2"> <rect class="table_number" x="171" y="56" width="84" height="69"></rect> </a> <a xlink:href="https://www.store.com/products/link3"> <rect class="table_number" x="292" y="59" width="82" height="65"></rect> </a> <a xlink:href="https://www.store.com/products/link4"> <rect class="table_number" x="408" y="59" width="85" height="70"></rect> </a> </svg> <script> getData(); async function getData() { try { const response = await fetch('myurl'); const data = await response.json(); // 解析API返回的JSON // 筛选出status为false的条目 const targetItems = data.documents.filter(item => !item.status); targetItems.forEach(item => { // 匹配对应url的<a>标签 const aTag = document.querySelector(`a[xlink:href="${item.url}"]`); if (!aTag) return; // --- 方案1:直接显示红色矩形 --- // const rect = aTag.querySelector('.table_number'); // if (rect) rect.style.opacity = '1'; // --- 方案2:替换为叉号(推荐)--- const rect = aTag.querySelector('.table_number'); if (!rect) return; // 获取矩形的位置和尺寸 const x = parseFloat(rect.getAttribute('x')); const y = parseFloat(rect.getAttribute('y')); const width = parseFloat(rect.getAttribute('width')); const height = parseFloat(rect.getAttribute('height')); // 计算叉号的中心坐标和长度 const centerX = x + width / 2; const centerY = y + height / 2; const crossLength = Math.min(width, height) * 0.35; // 创建SVG叉号路径 const crossPath = document.createElementNS('http://www.w3.org/2000/svg', 'path'); crossPath.setAttribute('class', 'table-cross'); crossPath.setAttribute('d', ` M ${centerX - crossLength} ${centerY - crossLength} L ${centerX + crossLength} ${centerY + crossLength} M ${centerX + crossLength} ${centerY - crossLength} L ${centerX - crossLength} ${centerY + crossLength} `); // 隐藏原矩形,添加叉号 rect.style.display = 'none'; aTag.appendChild(crossPath); }); } catch (error) { console.error('数据获取失败:', error); } } </script>
关键说明
- API数据处理:通过
response.json()解析返回数据,过滤出符合status: false的条目 - 元素匹配:使用属性选择器精准定位对应URL的
<a>标签 - 叉号实现:
- 基于原矩形的位置和尺寸计算叉号的居中位置,保证适配不同大小的区域
- 用SVG的
<path>绘制叉号,保留原<a>标签的跳转功能
- 兼容性:使用
createElementNS创建SVG元素,确保跨浏览器正常渲染
内容的提问来源于stack exchange,提问作者Coc L
相关产品推荐
相关产品推荐

