我尝试根据
中的示例从现有 SVG 对象分配背景图像http://codepen.io/progers/pen/CAEks
// Short script to encode our SVG in base64
// This can be reversed using window.atob('base64')
var code = document.getElementById('code');
var demo = document.getElementById('demo');
var svg = document.getElementsByTagName('svg')[0];
// Convert the SVG node to HTML.
var div = document.createElement('div');
div.appendChild(svg.cloneNode(true));
// Encode the SVG as base64
var b64 = 'data:image/svg+xml;base64,'+window.btoa(div.innerHTML);
var url = 'url("' + b64 + '")';
code.innerHTML = 'Base64 CSS (for cross-browser compatibility)\n\nbackground-image: ' + url + ';';
demo.style.backgroundImage = url;
我创造了这个
http://jsfiddle.net/bj0e063q/1/ jsfiddle。
不同之处在于,在 codepen 使用的是静态 svg,而我想通过代码动态创建它。为什么我的示例不起作用?
最佳答案
您的代码有效,它只是没有运行,因为 fiddle 已经在窗口加载时执行,并且因为您需要在设置 svg 之前定义 window.socialSharing
。
编辑:
显然,为了让它工作,你需要在 div 上设置背景图像,并在 svg 上设置 xmlns
属性(虽然在 IE 中这个属性是自动添加的,所以你必须检查它的存在):
svg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
检查此更新 fiddle .
关于javascript - 如何从现有的 svg 对象分配 css 背景图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29153981/