简体   繁体   中英

How to redraw SVG after change from javascript (Internet Explorer and Edge)

Does anyone know how to force IE and Edge to display/refresh embedded SVG after changing its content (see code below)

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Title</title>
        <script type="text/javascript">     
            function onClick() {           
                document.getElementById('svg').innerHTML = '<circle r="50" cx="50" cy="50" fill="red" />';
            }
        </script>
    </head>
    <body>  
        <button type="button" onclick="onClick()" >Display red circle</button>
        <svg id="svg"/>
    </body>
</html>

Modify your markup as

<div id="container">
  Your svg here
</div>

and add

document.getElementById("container").innerHTML += "";

at the end of your script.

As it was mentioned by @rzelek, SVG image will get updated on it's own if you add elements with svg.appendChild() rather than by assigning to svg.innerHTML .

One caveat, though: you must specify the http://www.w3.org/2000/svg namespace on the element you create using document.createElementNS() , instead of the normal createElement() .

Example:

const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
circle.setAttribute('r', '50');
circle.setAttribute('cx', '50');
circle.setAttribute('cy', '50');
circle.setAttribute('fill', 'red');
document.getElementById('svg').appendChild(circle);

JSFiddle

Basically, you do not need to reload anything. Actually, the problem is different. You will not able to interact with SVG using standard innerHTML method. Your SVG is not updated after calling to innerHTML . This method is suitable for editing HTML elements only.

Plase take a look at this: update SVG dynamically

Plunker

JS:

var x = 0; 

function onClick() {        
  var div = document.getElementById('svg');
  Update(div);
}

function Update(div){

  x++;

  div.innerHTML = '<svg><circle r="' + x + '" cx="' + x +'" cy="' + x + '" fill="red" /></svg>';

  if (x < 100)
  {
    setTimeout(function() {
      Update(div);
    }, 100);  
  }

  console.log(div.innerHTML);
}

HTML:

<body>
  <button type="button" onclick="onClick();" >Display red circle</button>
    <div id="svg">
    </div>
</body>

Wrapping the SVG in a container and then updating the content of the container seems to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM