简体   繁体   English

在不影响内部内容的情况下更改div的宽度

[英]Change width of div without affecting contents inside

I would like to create a set of svg images and place it in a div. 我想创建一组svg图像并将其放置在div中。 When that div gets resized (in javascript), I want the width to change, without changing what's inside it, giving the effect of the resized div covering up the contents (ex. cutting the div's width in half will make half the content inside hidden). 当该div调整大小(在javascript中)时,我希望更改宽度,而不更改其内部内容,从而提供调整后的div覆盖内容的效果(例如,将div的宽度减半将使隐藏的内容一半)。

Is this possible through html? 是否可以通过html?

Here is a js fiddle . 这是一个js小提琴 When you push the button, the div width changes to a smaller size. 当您按下按钮时,div宽度将更改为较小的尺寸。 I want it to hide the portion of the svg outside of it. 我希望它隐藏svg的一部分。

<div id="container">

 <svg width="400" height="280">
  <rect x="50" y="20" rx="20" ry="20" width="150" height="150" style="fill:red;stroke:black;stroke-width:5;opacity:0.5"></rect>


  <rect x="90" y="50" rx="20" ry="20" width="150" height="150" style="fill:blue;stroke:black;stroke-width:5;opacity:0.5"></rect>
 </svg>

</div>

This is a quick fix with just CSS, no JavaScript needed. 这是使用CSS的快速修复,不需要JavaScript。 You can hide what "overflows" with the overflow property. 您可以使用overflow属性隐藏哪些“溢出”。

Add overflow hidden to #container : 将隐藏的溢出添加到#container

#container{
    width:50%;
    background-color:white;
    overflow: hidden;
}

You can try this again with your fiddle modified 您可以在修改小提琴后再试一次

Also, there are a couple of other things going on in your fiddle: You are not using == in your conditional statements. 另外,您的小提琴还有其他几件事:您在条件语句中没有使用== And even if you were, you need a way to start things off with a dynamic width. 即使您是,也需要一种以动态宽度开始的方法。 So, here's a fixed up fiddle that uses just the JS changes. 因此,这是一个固定的小提琴 ,仅使用JS更改。

Lastly, I would do it slightly different in the way that I would add / remove classes based on if that class is already added to that element. 最后,我会根据是否已将类添加到该元素来添加/删除类,在方式上稍有不同。 You can check that out here on this fiddle 您可以在此提琴上查看一下

Add overflow:hidden or overflow:scroll to your CSS 将overflow:hidden或overflow:scroll添加到您的CSS

#container{
  width:50%;
  background-color:red;
  Overflow:hidden;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM