SVG <view>元素引用内容未正常显示问题求助
问题:SVG 元素片段标识符无法生效,仅显示青色圆形
根据相关说明,SVG的<view>元素可定义视图区域,当URL中的ID匹配<view>的ID时,其viewBox应该生效,实现局部视图的显示。但测试后无法达到预期效果,实际运行仅青色圆形显示。
测试用SVG文件代码
<svg viewBox="0 0 500 100" width="100" height="100" xmlns="http://www.w3.org/2000/svg"> <view id="one" viewBox="0 0 100 100"> <circle cx="50" cy="50" r="40" fill="red" /> </view> <view id="two" viewBox="0 0 100 100"> <circle cx="50" cy="50" r="40" fill="green" /> </view> <view id="three" viewBox="0 0 100 100"> <circle cx="50" cy="50" r="40" fill="blue" /> </view> <view id="four" viewBox="200 0 100 100" > <circle cx="250" cy="50" r="40" fill="yellow" /> </view> <view id="five" viewBox="300 0 100 100" /> <circle cx="350" cy="50" r="40" fill="cyan" /> <circle cx="50" cy="50" r="20" fill="black" /> </svg>
调用的HTML代码
<!DOCTYPE html> <html> <head> <style> img {border:1px solid #080;} img.red {content:url("foo.svg#one");} img.green {content:url("foo.svg#two");} img.blue {content:url("foo.svg#three");} </style> </head> <body> <img class="red" /> <img class="green" /> <img class="blue" /> <img src="foo.svg#four" /> <img src="foo.svg#five" /> </body> </html>
问题原因分析
<view>不是容器元素,不能包裹图形元素<view>是SVG的元数据元素,仅用于定义视图区域,本身不会渲染任何内容,其内部的子元素会被浏览器忽略。你把红、绿、蓝、黄色的<circle>放在<view>内部,这些图形根本不会被渲染出来。片段标识符匹配
<view>的作用逻辑
当URL使用#+<view>ID时,SVG会应用该<view>定义的viewBox来裁剪、缩放整个SVG的内容,但不会只显示<view>内部的元素(因为<view>本就不该包含元素)。当前代码的具体问题
- 前三个
<view>里的红、绿、蓝圆被放在<view>内,无法被渲染,调用#one/#two/#three时,只能看到SVG根元素里的黑色小圆和青色大圆(青色大圆在<view>外,会正常显示)。 #four对应的黄色圆同样在<view>内,无法渲染,调用时还是显示青色大圆。#five的viewBox定义为300 0 100 100,正好覆盖了青色圆的位置(cx=350处于300-400的x范围),所以会显示青色圆,这就是你看到的唯一效果。
- 前三个
正确实现方式
把所有图形元素放在<svg>根元素下,<view>仅单独定义viewBox,不包裹任何元素:
<svg viewBox="0 0 500 100" width="100" height="100" xmlns="http://www.w3.org/2000/svg"> <view id="one" viewBox="0 0 100 100" /> <view id="two" viewBox="100 0 100 100" /> <view id="three" viewBox="200 0 100 100" /> <view id="four" viewBox="300 0 100 100" /> <view id="five" viewBox="400 0 100 100" /> <circle cx="50" cy="50" r="40" fill="red" /> <circle cx="150" cy="50" r="40" fill="green" /> <circle cx="250" cy="50" r="40" fill="blue" /> <circle cx="350" cy="50" r="40" fill="yellow" /> <circle cx="450" cy="50" r="40" fill="cyan" /> <circle cx="50" cy="50" r="20" fill="black" /> </svg>
同时,建议优先使用<img>的src属性加载SVG片段,CSS的content:url()在部分浏览器存在兼容性问题。
内容的提问来源于stack exchange,提问作者rhavin
相关产品推荐
相关产品推荐

