简体   繁体   中英

How to apply ResizeObserver to SVG-Element?

I like to react to changes of the size of an SVG element in an HTML document. After some research, I found the ResizeObserver API that is intended for listening for such changes regarding a given HTML or SVG element ( stackoverflow ,MDN ). Unfortunately, I couldn't make it work for the SVG element.

My example contains a DIV element, an SVG element and for each of them a ResizeObserver:

 const svg = document.querySelector('#svg') const svgInfo = document.querySelector('#svg-info') const div = document.querySelector('#div') const divInfo = document.querySelector('#div-info') const svgObserver = new ResizeObserver(() => { svgInfo.textContent = svg.clientWidth }) svgObserver.observe(svg) const divObserver = new ResizeObserver(() => { divInfo.textContent = div.clientWidth }) divObserver.observe(div)
 <svg id="svg" style="background-color: red; width: 100%; height: 50px"></svg> <div id="svg-info">initial</div> <div id="div" style="background-color: blue; width: 100%; height: 50px"></div> <div id="div-info">initial</div>

I expect that both ResizeObservers trigger when resizing the elements, eg, by resizing the window. This would be visible due to changes of both info labels. Yet, for me (Mozilla Firefox 84.0), only the info label for the DIV element changes.

As a workaround, I can think of wrapping my SVG with a DIV as a proxy. Nevertheless, I still wonder why the combination of ResizeObserver and SVG does not work.

You will have to wrap the SVG inside a DIV element an observe the the wrapping DIV element, like so:

 const svg = document.querySelector('#svg') const svgInfo = document.querySelector('#svg-info') const div = document.querySelector('#div') const divInfo = document.querySelector('#div-info') const svgObserver = new ResizeObserver(() => { svgInfo.textContent = svg.clientWidth }) svgObserver.observe(svg) const divObserver = new ResizeObserver(() => { divInfo.textContent = div.clientWidth }) divObserver.observe(div)
 <div id="svg" style="background-color: red; width: 100%; height: 50px"> <svg style="width: 100%; height: 100%"></svg> </div> <div id="svg-info">initial</div> <div id="div" style="background-color: blue; width: 100%; height: 50px"></div> <div id="div-info">initial</div>

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