如何在页面中多次使用一个SVG文件

时间:2018-11-15 14:50:28

标签: javascript html svg owl-carousel owl-carousel-2

我有简单的猫头鹰传送带-

<div id="header-slider" class="owl-carousel owl-theme">
    <div class="single_slide" data-dot='<button role="button" class="owl-dot"></button><?php include("inc/chart3.svg")?>'>
       <img src="assets/images/banner.jpg" alt="" title="">
    </div>
    <div class="single_slide" data-dot='<button role="button" class="owl-dot"></button><?php include("inc/chart3.svg")?>'>
        <img src="assets/images/banner.jpg" alt="" title="">
    </div>
</div>

我正在尝试包括svg文件(inc / chart3.svg)而不是普通的点。问题在于,仅加载了一个文件,而其他文件则不会显示。设置了“活动”类后,有什么方法可以显示每个svg文件并启动其动画?

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="16" height="16" viewbox="0 0 250 250" enable-background="new 0 0 
426.667 410" xml:space="preserve">
<path class="kruznice" transform="translate(125, 125) scale(.84)"/>
</svg>

<script>
 jQuery(document).ready(function() {
 var kruznice = document.querySelector(".kruznice")
 , a = 0
 , p = Math.PI
 , t = 2;

(function draw() {
a++;
a %= 360;
var r = ( a * p / 180 )
, x = Math.sin( r ) * 125
, y = Math.cos( r ) * - 125
, mid = ( a > 180 ) ? 1 : 0
, anim = "M 0 0 v -125 A 125 125 1 "
+ mid + " 1 "
+  x  + " "
+  y  + " z";
kruznice.setAttribute( "d", anim );
setTimeout(draw, t); // Redraw
})();});
</script>

1 个答案:

答案 0 :(得分:4)

您可以同时加载它们,这不是问题。

问题在于querySelector仅返回一个元素,因此您的脚本仅应用于一个SVG元素。

改为使用getElementsByClassName(返回对象列表),然后使用Object.values()获取每个SVG元素,然后应用属性来运行动画。

$(document).ready(function() {
  var kruznice = document.getElementsByClassName("kruznice"),
    a = 0,
    p = Math.PI,
    t = 2;

  (function draw() {
    a++;
    a %= 360;
    var r = (a * p / 180),
      x = Math.sin(r) * 125,
      y = Math.cos(r) * -125,
      mid = (a > 180) ? 1 : 0,
      anim = "M 0 0 v -125 A 125 125 1 " +
      mid + " 1 " +
      x + " " +
      y + " z";
    Object.values(kruznice).forEach(item=>item.setAttribute("d", anim));
    setTimeout(draw, t); // Redraw
  })();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="16" height="16" viewbox="0 0 250 250" enable-background="new 0 0 
426.667 410" xml:space="preserve">
<path class="kruznice" transform="translate(125, 125) scale(.84)"/>
</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="16" height="16" viewbox="0 0 250 250" enable-background="new 0 0 
426.667 410" xml:space="preserve">
<path class="kruznice" transform="translate(125, 125) scale(.84)"/>
</svg>