2011-03-15 57 views
7

我想創建一個元素,它非常薄,而且非常高。我希望元素始終可見,即使您向右滾動。它應該是位置:固定在右邊,並且離開,但它應該是可滾動的。 我用谷歌搜索,但找不到解決問題的適當方法。 我只找到這個網站: http://demo.rickyh.co.uk/css-position-x-and-position-y/ 這正是我想要的,但我使用的是jQuery,而不是MooTools。我在jQuery中尋找相同的功能。我真的不想使用2個框架。有誰知道幫助?什麼?我一直在尋找幾個小時,但我無法在jQuery中找到符合我需要的東西。位置:同時固定和絕對。怎麼樣?

回答

17

下面是用jQuery

jsfiddle demo

的HTML

<div style="width:1000px;height:1000px;"> 
    <div id="box1" class="box" style="left:20px;top:20px;"> 
     My position-x is fixed but position-y is absolute. 
    </div> 
    <div id="box2" class="box" style="left:20px;top:120px;"> 
     My position-x is absolute but position-y is fixed. 
    </div> 
    <div id="box3" class="box" style="left:20px;top:220px;"> 
     Im positioned fixed on both axis. 
    </div> 
</div> 

代碼

$(window).scroll(function(){ 
    var $this = $(this); 
    $('#box1').css('top', 20 - $this.scrollTop()); 
    $('#box2').css('left', 20 - $this.scrollLeft()); 
}); 

和一些CSS的解決方案

.box 
{ 
    width:400px; 
    height:80px; 
    background:gray; 
    position:fixed; 
} 
+3

很棒!!!這正是我需要的!非常感謝你!!! – Mischka 2011-03-15 20:57:51

+0

@Mischka:請點擊綠色的勾號來接受這個答案。 – stealthyninja 2011-03-15 21:04:27

+1

你是忍者。 – Beachhouse 2013-05-10 14:45:55

2

根據以前的答案,我幫助了我正在嘗試做的事情,保留位置固定的標題div,固定位置x的左側div和內容div,它們將在x和年。

想我會後我的情況下,任何人的jsfiddle發現它有用:

My jsfiddle demo

的HTML

<body> 
<div style="width:5000px;height:1000px;"> 
    <div id="box1" class="box"> 
     My position-x is fixed but position-y is scrollable. 
    </div> 
    <div id="box2" class="box"> 
     My position-y is scrollable but position-x is fixed. 
    </div> 
    <div id="box3" class="box"> 
     My position-x and position-y are both scrollable. 
    </div> 
</div> 

代碼

$(window).scroll(function(){ 
    var $win = $(window); 
    $('#box2').css('top', 0 -$win.scrollTop()); 
    $('#box1').css('left', 120 -$win.scrollLeft()); 
    $('#box3').css('left', 120 -$win.scrollLeft()); 
    $('#box3').css('top', 20 -$win.scrollTop()); 
}); 

The CSS

.box { 
    position:fixed; 
} 
#box1 { 
    top: 0px; 
    left: 120px; 
    width: 1000px; 
    height: 20px; 
    background-color: #FF0000; 
    z-index:150; 
} 
#box2 { 
    top: 0px; 
    left: 0px; 
    width: 120px; 
    height: 520px; 
    background-color: #00FF00; 
    z-index:200; 
} 
#box3 { 
    top: 20px; 
    left: 120px; 
    width: 1000px; 
    height: 500px; 
    background-color: #0000FF; 
    color: white; 
    z-index:100; 
} 
相關問題