我可以使用 JavaScript SVG 库将 SVG 图像显示为 div 背景吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7308883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 23:42:28  来源:igfitidea点击:

Can I display an SVG image as a div background with a JavaScript SVG library?

javascriptjqueryhtmlsvg

提问by aknuds1

In an HTML page, I want to use an SVG image as a background in a divelement, with a preelement with text on top of of it (the background). The background image should scale with the containing div, while maintaining aspect ratio.

在 HTML 页面中,我想使用 SVG 图像作为div元素中的背景,并pre在其顶部(背景)有一个带有文本的元素。背景图像应与包含的一起缩放div,同时保持纵横比。

Can I accomplish this task with one of the SVG JavaScript libraries, such as jQuery SVG/ Rapha?l/ svgweb?

我可以使用 SVG JavaScript 库之一完成此任务,例如jQuery SVG/ Rapha?l/ svgweb吗?

The kind of structure I'd like to add a background image to:

我想添加背景图像的结构类型:

<div>
  <pre>Some text...</pre>
</div>

回答by robertc

You can use an SVG image as a CSS background, providing you only want to support recent browsers, use background-sizeto scale the image and maintain the aspect ratio. Here the image is applied directly to the pre, just to demonstrate:

您可以使用 SVG 图像作为 CSS 背景,前提是您只想支持最近的浏览器,用于background-size缩放图像并保持纵横比。这里的图像直接应用于pre,只是为了演示

pre {
    outline: 2px dashed black;
    padding: 1em;
    background-image: url(http://upload.wikimedia.org/wikipedia/commons/8/84/Konqi_svg.svg);
    background-repeat: no-repeat;
    background-size: cover;
}

If you want to support IE8 and FF3.6 then you'll have to resort to absolutely positioned elements as andrewmu suggests.

如果您想支持 IE8 和 FF3.6,那么您将不得不像 andrewmu 建议的那样使用绝对定位的元素。

回答by andrewmu

You could always cheat and use position: absoluteto put two divs in the same place.

你总是可以欺骗并使用position: absolute将两个divs 放在同一个地方。

回答by austinbv

SVG images are part of the DOM they cannot be a div background, instead they are an element just like a div.

SVG 图像是 DOM 的一部分,它们不能作为 div 背景,而是像 div 一样是一个元素。

You could place an SVG image behind a transparent div to get the illusion of a background. This just involves positing your SVG and content in the proper place.

您可以将 SVG 图像放在透明 div 后面以获得背景的错觉。这仅涉及将您的 SVG 和内容放置在适当的位置。

to get scaling you should use some math to maintain aspect ratio, should be pretty easy, the word ratio is involved. That would be a clue on how to do that.

要获得缩放,您应该使用一些数学方法来保持纵横比,应该很容易,涉及到比率这个词。这将是如何做到这一点的线索。

EDIT

编辑

It looks like I was wrong http://www.broken-links.com/2010/06/08/using-svg-in-background-image/it can be a background.

看起来我错了 http://www.broken-links.com/2010/06/08/using-svg-in-background-image/它可以是背景。