简体   繁体   中英

Javascript – Change SVG viewBox with Modernizr Media Queries

i'm trying to change the values of an svg viewbox with javascript and modernizr media queries. however, this is not working. what am i doing wrong?

<script type="text/javascript">
      var svgRoot = document.getElementById('svg1');
        var vbValue = '0 0 10 10';

            if (Modernizr.mq('(max-width: 700px)')) {
            svgRoot.setAttribute('viewBox', vbValue);

            }

            else {
            }




</script>

There are quite a few changes you need to make in order to get this to work, the changes required are in your HTML, SVG File and Javascript Code,

HTML:

Your SVG image needs to be inside object Tags with an id.

For example lets say your Id is "hello"

<object id="hello" data="../images/svg1" type="image/svg+xml" >

(I'm assuming SVG1 is the name of your svg file).

Javascript:

window.onload = function() {
$(window).on('resize', function(){

var a = document.getElementById("hello"); // get the element by the object tag id, not the name of the SVG file


var svgDoc = a.contentDocument;

var svgItem = svgDoc.getElementsByTagName("svg")[0]; //copy these exactly, don't change ("svg")[0];

if (Modernizr.mq("screen and (max-width:700px)")) { // change the width to whatever you require - must be written in this format though "screen and (max-width:)"))

svgItem.setAttribute("viewBox", "466.3 0 336.6 232.9"); //change the view box to what you require

} 
else {
   svgItem.setAttribute("viewBox", "0 0 1269.2 232.9"); //change the     view box to what you require
}
 });
 };

SVG File:

http://plnkr.co/edit/vV8RUt?p=preview

Copy and paste all of the code in the svg.svg file (from the top of the file down until you get to the SVG elements) into the top of your svg file. You have to re add some script tags at the top, or at least i did, so have a play around here.

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