SVG将宽度填充到子元素 [英] SVG Fill Width to Child Elements

查看:114
本文介绍了SVG将宽度填充到子元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要我的容器SVG元素进行缩放,以适应其子组元素,或者它在溢出时显示滚动条。我想知道是否有css属性为了这样做。



例如。如果标记如下所示:

 < div class =wrapperstyle =width:500px; overflow-x :scroll;> 
< svg class =main>
< g width =1000>< / g>
< / svg>
< / div>

如果子元素超过它,我可以得到svg的宽度填充到1000或滚动条宽度?



以下css对上述没有影响:

 。 main {
width:500px; //设置为100%也不做什么
overflow-x:scroll;
}

我现在通过更新svg容器的宽度, ;但是这是麻烦和容易出错,因为我需要检查,以确保当任何新的元素添加在svg内,svg容器调整大小适合。



任何帮助将非常感激。

解决方案

没有办法让SVG自动更新其宽度和高度添加元素。您可以自己手动更新宽度和高度。



但是,不必每次添加新内容时都更新SVG宽度和高度,添加一个间隔计时器函数来为你检查。

  setInterval(mySVGCheckFn,500); 

function mySVGCheckFn()
{
var svg = document.getElementById(mysvg);
var bbox = svg.getBBox();

//为某些呼吸空间添加10个填充
svg.setAttribute(width,bbox.x + bbox.width + 10);
svg.setAttribute(height,bbox.y + bbox.height + 10); rel =nofollow>此处演示



点击添加更多将随机圆添加到SVG。



DOM2添加了一些事件类型,当您向DOM添加节点时应该触发这些事件类型。他们将是理想的解决方案,但我相信它们不可靠地支持所有浏览器。


I'd like my container SVG element to scale in order to fit its child group elements or for it to present scrollbars on overflow. I was wondering if there was a css property in order to do so.

E.g. If the markup looks like the following:

<div class="wrapper" style="width:500px; overflow-x:scroll;">
   <svg class="main">
      <g width="1000"></g>
   </svg>
</div>

How might I get the svg's width to fill to '1000' or present scrollbars if child elements exceed its width?

The following css has no effect on the above:

.main {
    width: 500px; // Setting to 100% also does nothing
    overflow-x: scroll;
}

I currently achieve the desired effect with javascript by updating the svg container's width as necessary; but this is cumbersome and error-prone, as I'd need to check to make sure that when any new element is added inside svg, that the svg container resizes to fit.

Any help would be much appreciated.

解决方案

There is no way to have the SVG automatically update its width and height when you add elements to it. All you can do is manually update the width and height yourself.

However, rather than having to remember to update the SVG width and height every time you add something, you could add an interval timer function to do the check for you.

setInterval(mySVGCheckFn, 500);

function  mySVGCheckFn() 
{
    var  svg = document.getElementById("mysvg");
    var  bbox = svg.getBBox();

    // Add 10 padding for some breathing space    
    svg.setAttribute("width", bbox.x + bbox.width + 10);
    svg.setAttribute("height", bbox.y + bbox.height + 10);
}

Demo here

Click 'Add more' to add random circles to the SVG.

DOM2 added some event types that are supposed to be fired when you add nodes to the DOM. They would be the ideal solution, however I believe they aren't supported reliably across all browsers.

这篇关于SVG将宽度填充到子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆