我的页面上有一个粘性页脚,但是如果启用了javascript,SVG文件将不会显示在chrome中,这样可以确保SVG图像在悬停时改变颜色。删除javascript会导致Chrome加载图片。
我无法在jsfiddle中重新创建效果,但这里是代码: https://jsfiddle.net/r9szd060/
这是javascript代码:
$( document ).ready( function () {
$( 'img[src$=".svg"]' ).each( function () {
var $img = jQuery( this );
var imgURL = $img.attr( 'src' );
var attributes = $img.prop( "attributes" );
$.get( imgURL, function ( data ) {
// Get the SVG tag, ignore the rest
var $svg = jQuery( data ).find( 'svg' );
// Remove any invalid XML tags
$svg = $svg.removeAttr( 'xmlns:a' );
// Loop through IMG attributes and apply on SVG
$.each( attributes, function () {
$svg.attr( this.name, this.value );
} );
// Replace IMG with SVG
$img.replaceWith( $svg );
}, 'xml' );
} );
} );
我尝试使用embed标记而不是img标记,但这并没有改变chrome中的行为。 Firefox(桌面+ iOS + Android)可以很好地处理SVG图像,Safari(桌面+ iOS)也是如此。 SVG图像在桌面上的Chrome和Android上的chrome中消失。奇怪的是,iOS上的chrome确实有用......
我认为它与通过javascript处理SVG的方式以及如何保存SVG有关,但我在javascript中不够精通以了解问题。我读过Chrome有时会出现SVG文件的问题吗?我不知道如何上传SVG文件本身,以便您可以看到,但如果有人可以告诉我如何传递相关信息(例如从插图中打开的文件)我会将其添加到此帖子:)。
有谁知道问题是什么以及如何解决?
答案 0 :(得分:1)
您不能使用CSS设置任何SVG样式,您必须为其设置宽度的属性。这就是为什么你没有在页面中看到它们,每个SVG都采用他的真实尺寸(大约600px。)
$( document ).ready( function () {
$( 'img[src$=".svg"]' ).each( function () {
var $img = jQuery( this );
var imgURL = $img.attr( 'src' );
var attributes = $img.prop( "attributes" );
$.get( imgURL, function ( data ) {
// Get the SVG tag, ignore the rest
var $svg = jQuery( data ).find( 'svg' );
// Remove any invalid XML tags
$svg = $svg.removeAttr( 'xmlns:a' );
// Loop through IMG attributes and apply on SVG
$.each( attributes, function () {
$svg.attr( this.name, this.value );
} );
//Add width on newly created svg
$svg.attr('width', '30');
// Replace IMG with SVG
$img.replaceWith( $svg );
}, 'xml' );
} );
} );