0
matchMedia()
JavaScript Web APIを使用して、SVGにメディアクエリの効果を作成しようとしています。私は単一のメディアクエリで動作するようにしましたが、以前に書かれた方法(異なる名前の関数を書き出す方法)はうまく拡張できませんでした。私はこれを試しましたが、動作させることができません - 何が欠けていますか?応答可能なviewBoxサイズ変更のために複数のmatchMedia()をSVGで使用する
// 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");
}
}
}