SAP(AngularJS和Angular Route)具有由svg-sprite制作的基于图标的导航。所以,我有这样的内联代码:
<div style="height: 0; width: 0; position: absolute; visibility: hidden">
<svg xmlns="http://www.w3.org/2000/svg">
<symbol id="icon-grid-32" viewBox="0 0 32 32">
<g stroke-width="2" stroke-linecap="round" stroke-miterlimit="10" stroke-linejoin="round">
<path d="M2 2h11v11H2zM19 2h11v11H19zM2 19h11v11H2zM19 19h11v11H19z"/>
</g>
</symbol>
</svg>
</div>
导航中的图标如下:
<a href=""><svg class="icon icon-32 outline black"><use xlink:href="#icon-grid-32"></use></svg></a>
我在此导航中看到的所有内容都没有,<use>
的大小为0×0像素。我知道Firefox bug with xml:base,但添加xml:base对我没有帮助。您可以尝试以下示例:http://css.yoksel.ru/assets/demo/svg-in-firefox/svg-has-base.html
适用于Firefox,Safari和其他浏览器,但不适用于Chrome 49+(48版本没有此问题)。
答案 0 :(得分:5)
这是由AngularJS对<base href="/" />
的依赖性和UI路由的组合引起的,当应用程序未处于“根”状态时,<use>
元素中的相对散列链接将无法正确解决。
要解决此问题,您需要解析xlink:href
以使用绝对路径。您可以执行以下操作:
<强>角图标-template.html 强>
<svg class="c-icon" viewBox="0 0 32 32">
<use xlink:href="" ng-attr-xlink:href="{{baseUrl + '#' + iconName}}" />
</svg>
<强>角icon.js 强>
angular.module('angularIcon', [])
.directive('angularIcon', {
templateUrl: 'angular-icon-template.html',
scope: { iconName: '@' },
controller: function($scope) {
$scope.baseUrl = window.location.href.replace(window.location.hash, '');
}
});
答案 1 :(得分:1)
我遇到了与您描述的问题非常相似的问题,但我会在指令中生成我的图标<svg>
和<use>
。
我一直在寻找今天更好的部分的答案,并提出了<use>
和xlink:href
问题的解决方法。这只是通过内联想要的svg来重新创建功能。
为简单起见,我假设我有<angular-icon>
指令,通过属性icon-name
<angular-icon icon-name="{{someObject.iconName}}">
工作指令现在看起来如下:
angular.module('angularIcon', [])
.directive('angularIcon', IconDirective);
function IconDirective(){
return{
template:'',
templateNamespace:'svg',
link:function(scope, element, attributes){
// my icon name comes from $http call so it doesnt exist when initialising the directive,
attributes.$observe( 'iconName', function(iconName){
// let's grab the icon from the sprite
var icon = angular.element( document.getElementById( iconName ) );
// let's clone it so we can modify it if we want
var iconClone = icon.clone();
var namespace = "http://www.w3.org/2000/svg";
// manually create the svg element and append the inlined icon as no other way worked
var svg = document.createElementNS( namespace, 'svg' );
svg.setAttribute( 'viewBox', '0 0 32 32' );
svg.setAttribute( 'xml:space', 'preserve' );
svg.appendChild( iconClone[0] );
// let's add the newly created svg+icon to the directive's element
element[0].appendChild( svg );
});
},
scope:{
iconName: '@'
}
}
}