javascript - 如何附加一个
问题描述
以下 vanilla Javascript 代码附加了一个<svg>
和一个<style>
元素
var text="";
text=text+"<defs>"
text=text+"<filter id='Matrix' filterUnits='objectBoundingBox' x='0%' y='0%' width='100%' height='100%'>"
text=text+"<feColorMatrix type='matrix' in='SourceGraphic' values='0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0'/>"
text=text+"</filter>"
text=text+"</defs>"
var tag;
tag = document.createElement("svg");
document.body.appendChild(tag);
tag.innerHTML=text;
tag = document.createElement("style");
document.body.appendChild(tag);
tag.innerHTML="img.free {filter:url('#Matrix')}";
在以下 html 代码中从图像中删除红色:
<head>
</head>
<body>
<img class="free" src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/500px-Google_2015_logo.svg.png">
</body>
(这里是jsfiddle )
<svg>
但是,不应用元素内部的过滤器。
请注意,页面的静态版本(此处为 jsfiddle )没有此类问题。
如何<svg>
通过 Javascript 注入元素并使过滤器工作?
解决方案
SVG 元素必须在 SVG 命名空间中创建。
var text="";
text=text+"<defs>"
text=text+"<filter id='Matrix' filterUnits='objectBoundingBox' x='0%' y='0%' width='100%' height='100%'>"
text=text+"<feColorMatrix type='matrix' in='SourceGraphic' values='0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0'/>"
text=text+"</filter>"
text=text+"</defs>"
var tag;
tag = document.createElementNS("http://www.w3.org/2000/svg", "svg");
document.body.appendChild(tag);
tag.innerHTML=text;
tag = document.createElementNS("http://www.w3.org/2000/svg", "style");
document.body.appendChild(tag);
tag.innerHTML="img.free {filter:url('#Matrix')}";
<head>
</head>
<body>
<img class="free" src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/500px-Google_2015_logo.svg.png">
</body>
推荐阅读
- python - 使用现代 OpenGL 绘图时的点云失真
- python - 如何在Python中获取变量的内存位置
- typescript - 如何定义这个打字稿接口类型
- go - 是否可以获得返回值的源代码行?
- java - 在android studio中上传图片
- wildfly - Javax.naming.NameNotFoundException:尝试在 JavaEE 和 Wildfly 中查找 jndi 名称时
- mysql - 如何使用 Antlr4 的访问者模型在翻译器中添加注释/空格
- html - 为什么我的按钮将我带到页面顶部,为什么它只允许我点击最左边的边缘?
- c++ - char* 和 void* 在所有情况下都可以互换用作缓冲区吗?C++
- flutter - 错误:无法调用需要 const 表达式的非“const”构造函数