2017-10-14 69 views
0

我正嘗試使用matchMedia() JavaScript web API在SVG上創建媒體查詢的效果。我用它來處理單個媒體查詢,但它之前編寫的方式(寫出不同名稱的函數)沒有很好地擴展。我試過這個,但是我無法讓它工作 - 我錯過了什麼?將多個matchMedia()與SVG用於響應式viewBox調整大小

// media query event handler 
if (matchMedia) { 

    var bg1 = document.getElementById("bg1-mbl"); 
    console.log(bg1) // returns expected SVG 

    var mqls = [ // list of window.matchMedia() queries 
     window.matchMedia("(min-width: 400px) and (max-width: 600px)"), 
     window.matchMedia("(min-width: 600px) and (max-width: 800px)"), 
     window.matchMedia("(min-windth: 800px) and (max-width: 1000px)") 
    ] 

    for (var i=0; i < mqls.length; i++){ // loop through queries 
     mqls[i].addListener(widthChange) // call handler function whenever the media query is triggered 
     widthChange(mqls[i]) // call handler function explicitly at run time 
    } 

    // media query change 
    function widthChange(mql) { 
     if (mqls[0].matches) { 
      console.log(mqls[0]) // returns expected 
      console.log("This is bg1: " + bg1) // returns "This is bg1: [object SVGSVGElement]"" 
      bg1.setAttribute("viewBox", "0 150 375 580"); 
     } 
     if (mqls[1].matches) { 
      console.log(mqls[1]) 
      bg1.setAttribute("viewBox", "0 400 375 580"); 
     } 
     if (mqls[2].matches) { 
      console.log(mqls[3]) 
      bg1.setAttribute("viewBox", "0 800 375 580"); 
     } 
     else { 
      // set to default viewBox values 
      bg1.setAttribute("viewBox", "0 0 375 580"); 
     } 
    } 

} 

回答

0

想通了!需要將if更改爲else if。完整的解決方案:

// RESPONSIVE SVG 

/* ==================================================== */ 
/* BG1 */ 
var bg1 = document.getElementById('bg1-mbl'); // grab svg element 

// media query event handler 
if (matchMedia) { 
    var mqls = [ // array of media queries 
     window.matchMedia("(min-width: 400px) and (max-width: 600px)"), 
     window.matchMedia("(min-width: 600px) and (max-width: 800px)"), 
     window.matchMedia("(min-width: 800px) and (max-width: 1000px)") 
    ] 

    for (i=0; i < mqls.length; i++) { // loop though media queries 
     mqls[i].addListener(WidthChange); // listen for queries 
     WidthChange(mqls[i]); // call handler func at runtime 
    } 
} 

// media query change 
function WidthChange(mql) { 

    /* For testing - xml elment to string 
    var XMLS = new XMLSerializer(); 
    var bg1XML = XMLS.serializeToString(bg1); 
    */ 

    if (mqls[0].matches) { 
     bg1.setAttribute("viewBox", "0 150 375 580"); 
    } 
    else if (mqls[1].matches) { 
     bg1.setAttribute("viewBox", "0 300 375 580"); 
    } 
    else if (mqls[2].matches) { 
     bg1.setAttribute("viewBox", "0 400 375 580"); 
    } 
    else { 
     // set default 
     bg1.setAttribute("viewBox", "0 0 375 580"); 
    } 
}