我的页面上有一个粘性页脚,但如果我启用确保 SVG 图像在悬停时改变颜色的 javascript,SVG 文件将不会显示在 chrome 中。删除 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 文件本身以便您可以看到,但如果有人能告诉我如何传递相关信息(例如从在 illustrator 中打开的文件)我会把它添加到这篇文章中:) .
有谁知道问题是什么以及我该如何解决?
最佳答案
您不能使用 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' );
} );
} );
关于javascript - 通过 javascript 脚本后,SVG 图像未显示在 Chrome 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45383202/