我正在尝试使用 javascript 和 modernizr 媒体查询更改 svg viewbox 的值。但是,这是行不通的。我做错了什么?
<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>
最佳答案
为了让它工作,您需要做很多更改,所需的更改在您的 HTML、SVG 文件和 Javascript 代码中,
HTML:
您的 SVG 图像需要位于带有 ID 的对象标签内。
例如假设您的 Id 是“你好”
<object id="hello" data="../images/svg1" type="image/svg+xml" >
(我假设 SVG1 是您的 svg 文件的名称)。
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 文件:
http://plnkr.co/edit/vV8RUt?p=preview
将 svg.svg 文件中的所有代码(从文件顶部向下直到到达 SVG 元素)复制并粘贴到 svg 文件的顶部。你必须在顶部重新添加一些脚本标签,或者至少我做了,所以在这里玩一玩。
关于Javascript – 使用 Modernizr 媒体查询更改 SVG viewBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34791378/