2013-06-24 53 views
0

所以我想只能显示元素的一半。现在,我可以做类似如下:在css中显示元素的一半

function half($elem,which){ 
    //here I would get the scrolling position 
    //of the element $elem along with the outer 
    //width and outer height. Then, depending on 
    //what 'which' is (left,right,top,bottom), the 
    //function would append an element with the same 
    //background color as the body background in 
    //order to cover the correct part of the element 
}; 

但是,这只是增加了额外的项目到DOM这将是不必要的,如果,在一些简单的CSS或JavaScript,我可以将它设置为只显示(或切出)只是一个元素的一部分。那可能吗?如果是这样,怎么样?

UPDATE:

大家都试图猜测,here is a fiddle是不断追加内容的容器后。为了回答我的问题,你需要有一个函数来修改被附加的特定div的css,以便它只追加指定的一半内容。

+1

如果是块元素,您可以将宽度/高度设置为其计算值的一半,然后设置“overflow:hidden;'。 – Paulpro

+0

然后有'剪辑':http://tympanus.net/codrops/2013/01/16/understanding-the-css-clip-property/(作品绝对定位元素只有寿) –

+0

同意。正如@Paulpro指出的那样,你可能需要溢出:隐藏,也许是一个容器去与它。 –

回答

2

我的意思是很难根据少量的信息您提供的,但这样的事情应该工作:

.ElementContainer { 
    width:500px; /* example, random number */ 
    overflow:hidden; /* important part */ 
} 

.Element { 
    width:200%; /* relative to parent, so double the width of parent */ 
} 

然后就是这样的:

<div class="ElementContainer"> 
    <img src="whatever.jpg" alt="" class="Element" /> 
</div> 

这应该只显示上半年,从左边。如果你想要做像...中间一半的东西,你就需要使用定位:

.ElementContainer { 
    position:relative; /* must declare position of parent */ 
    width:500px; 
    height:200px; /* since child is removed from DOM, it will be 0 height unless declared explicitly */ 
    overflow:hidden; 
} 

.Element { 
    width:200%; 
    position:absolute; 
    top:0; /* always declare both X & Y */ 
    left:-25%; /* can be any negative % you want, this is just an example */ 
} 

这会做这种集中亮相......你可以用它从这里跑,应该给你一个选项的想法。

+0

如果这样做很多,使用容器仍然会压倒DOM ... I看到这是有效的,并为+1,我会接受这个答案,如果没有别的出现,似乎是在实际的元素 –

+0

是的,我听到雅,你会有一大堆非语义的HTML只是为了这个目的的截止点,但它是我可以在飞行中想到的最好的。 – PlantTheIdea

-1

这是一种模糊的正是你想要的一半被削减,但我会用

background-size:cover; 
+0

我甚至不知道如何可能有一半...请解释你自己 –

+0

你的问题很不清楚。如果您将嵌套div的尺寸加倍并使用背景大小:封面,则会减半。 –

0

这很容易在CSS特定的像素高度后切断,开始假设你要削减垂直,替补宽度,如果你想水平切割:

.restricted {overflow: hidden; height: 45px; } 

看到这个的jsfiddle:http://jsfiddle.net/jrvf7/

后精确半元素的时候切断,如果你不事先不知道元素的高度,将需要一些JavaScript。查看其他提交的答案。如果可能,我建议你去我的CSS路线,但是。