简体   繁体   中英

How to make SVG responsive, with fixed elements?

The size of some UI elements are fixed; the size of other elements is responsive to the size of the container.

For example, a graph's text and legend is normally fixed size, but its axes' sizes are normally responsive.

 <svg font-size="14" height="200" width="100%" shape-rendering="crispEdges"> <rect x="30" y="10" width="120" height="30" stroke="black" fill-opacity="0"></rect> <text color="black" x="32" y="24">Legend</text> </svg> 

 <div style="font-size: 14px; height:200px; position:relative; width:100%"> <div style="position:absolute; top:10px; left:30px; width: 116px; height: 26px; border: 1px solid black; padding: 2px"> Legend </div> <div style="position:absolute; top:5px; left:5px; bottom: 5px; right:5px; border-left: 1px solid black; border-bottom: 1px solid black"> </div> </div> 

As far as I can tell, SVGs cannot do this. I can use JS and listen to the window resize event, though this event is not always fired, eg when printing.

Is is possible to have fixed and responsive elements in an browser SVG?

From what I'm getting out of your question, listening for a resize event is indeed not going to do the cut for printing. So what you need to do is listen for a print request, and run your resize code from it:

window.addEventListener("beforeprint", beforePrint);
window.addEventListener("afterprint", afterPrint);
if (window.matchMedia) {
    var mediaQueryList = window.matchMedia('print');
    mediaQueryList.addListener(function(mql) {
        if (mql.matches) {
            beforePrint();
        } else {
            afterPrint();
        }
    });
}

function beforePrint() {
    //Resize for printing
}

function afterPrint() {
    //Resize again for after printing
}

This is taken from this article . Please read over it for a more detailed description, limitations, and other possible work-arounds.

For any other situations where you need to resize but the window resize event isn't sufficient, there's usually at least a semi-simple work-around. JavaScript is your only option for something as complex as sorting and sizing items in a graph.

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