2012-05-04 196 views
5

我想在此css更改中添加或減去'top'的值。而不是指定一個特定的像素量我想添加20px到外部CSS提供的當前值。jQuery增量增加css值

目標是使列表向上移動。

$('.up').click(function(){ 
    $('.list').css('top','-20px'); 
}); 

的HTML

<div id="container"> 
    <ul class="list"> 
     <li >first item</li> 
     <li class="active">second item</li> 
     <li>third item</li> 
     <li >fourth item</li> 
    <ul> 
</div> 
<a href="#" class="up">up</a> 
<a href="#" class="up">down</a>​ 

回答

12

根據您的編輯:

$('.up').click(function(){ 
    $('.list').css({position:'absolute', top: parseInt($('.list').css('top'), 10) + 20 + 'px'}); 
}); 

或者你可以同時使用animate這樣每次單擊添加20px

$('.up').click(function(){ 
    $('.list').css({position:'absolute'}); 
    $('.list').animate({top: '+=20'}); 
}); 

top屬性不會工作,除非你還指定position

$('.up').click(function(){ 
    $('.list').css({position:'absolute', top:'-20px'}); 
}); 

變化positionabsoluterelative按您的需求。

請注意,如果您希望.list元素只出現在其容器內,同時改變top,你需要分配到position:relative父元素和absolute.list元素。

+0

非常感謝您的幫助! – patrick

+0

@帕特里克:不客氣 – Sarfraz

-2

$('.list').css('position','relative').css('top','-20px');

+0

錯誤的寫作方式jQuery,你可以有合併的CSS函數。 '$('。list')。css({'position':'relative','top':' - 20px'});' – Murtaza

+0

我只是想把更多的注意力放在'position'上。而且,它不是一個錯誤的方法,它也可以工作 –

+0

是的,它會產生正確的結果,但是你更喜歡在你的項目中使用相同的嗎?調用同一個函數兩次是錯誤的想法,而它可以在一箇中完成。 – Murtaza

0

更改「向上」全班學生分成不同的ID對按鈕

<a href="#" id="up">up</a> 
<a href="#" id="down">down</a>​ 

以容器的上邊距的當前值並進行修改:

$('#up').on('click', function(){ 
    currentValue = parseInt($('#container').css("margin-top")); 
    currentValue -= amount; 
    $('#container').css("margin-top", currentValue) 
}) 

$('#down').on('click', function(){ 
    currentValue = parseInt($('#container').css("margin-top")); 
    currentValue += amount; 
    $('#container').css("margin-top", currentValue) 
}) 
0

CSS是不是真的這樣做數學和操作,但更多的只是指定你的風格。這樣做的最佳方式是在javascript中,

getElementById("nameofyourelement").style['top'] = "5px" 

例如。使用CSS3動畫甚至會更好。這樣

getElementById("nameofyourelement").style['-webkit-transition-duration'] = "1s" //1 second duration for animation, set to 0 if you don't want animation 
getElementById("nameofyourelement").style['-webkit-transform'] = "translateY(5px)" 
1

爲一個完整的例子請參閱本的jsfiddle:http://jsfiddle.net/NYVmw/

$('.up').click(function(){ 
    var newtop = $('.list').position().top - 20; 
    $('.list').css('top', newtop + 'px'); 
}); 

$('.down').click(function(){ 
    var newtop = $('.list').position().top + 20; 
    $('.list').css('top', newtop + 'px'); 
}); 

+0

哇,我以爲我知道我想做什麼,但這對我來說是一場遊戲改變。非常感謝! – patrick

7

.css()該方法還允許 「+ =」 和 「 - =」 語法.animate()需要。所以你可以簡單地做到這一點:

$('.up').click(function(){ 
    $('.list').css('top','-=20px'); 
}); 
+0

這應該是最好的回答。 – JayD3e