[英]How can I access SVG elements in html (with CSS preferably) without pasting the code in directly?
[英]How can I access from CSS to the elements within the SVG file?
<object data = "img/img.svg" type = "image/svg + xml">...
"path"
和屬性"fill"
。 "fill"
使用不同的顏色。 必須使用div.red #pathId {fill: red}
和div.green #pathId {fill: green}
.red
和.green
在SVG和不可用=>它不適用) 有沒有不使用JS的解決方案? (使用JS,我們可以通過.contentDocument
獲取SVG的內容並設置fill屬性)
僅當SVG是HTML-DOM的元素時,您才能訪問SVG,如下所示:
<div class="svg">
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="566.93px" height="1133.858px" viewBox="0 0 566.93 1133.858" enable-background="new 0 0 566.93 1133.858" xml:space="preserve">...</svg>
</div>
這是我的一個項目的html代碼段。 在全局CSS中,有一些基本樣式:
.svg {
height: 400px;
width: 400px;
}
svg {
height: 100%;
width: 100%;
}
為了包括SVG,我使用以下機制:
HTML:
<div class="svg" data-svgpath="img/img.svg"></div>
JS:
function loadSvg(container) {
if (container.dataset.svgpath) {
$(container).load(container.dataset.svgpath, function(resp, status, xhr) {
container.classList.add('is-loaded');
});
}
}
加載SVG並注入DOM:
$('.svg').each(function() {
loadSvg(this);
});
這是我在項目中所做的簡短摘要,它的工作原理很吸引人。 我可以通過全局css和js進行訪問,因為我也可以控制SVG中組的可見性。
內嵌svg的瀏覽器支持非常好: http : //caniuse.com/#feat=svg-html5
編輯:啊,我的錯誤:您正在尋找沒有JS的解決方案。 嗯,對不起,但可能對您或其他人還是有幫助的。
喬·拉爾夫
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.