Javascript – 使用 Modernizr 媒体查询更改 SVG viewBox

标签 javascript svg modernizr viewbox

我正在尝试使用 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/

相关文章:

javascript - 具有非核心检测的自定义 grunt-modernizr

javascript - 设置间隔和延迟

jquery - 如何在可拖动和可放置之间画一条线?

javascript - 在 jQuery UI 和 jQuery Mobile 之间切换的最佳方式是什么

css - 如何使 'a' 标签中的 svg 图标始终位于左侧,文本位于其余部分的中间?

svg - 在 SVG 中缩放圆

javascript - 理解 modenizer 包含函数

php - 尝试创建一个具有不同文本的网页,具体取决于从菜单中选择的内容

JavaScript setTimeout 运行两次

javascript - jQuery 位置 DIV 固定在除主页外的滚动顶部