JQuery add css value gradually

I want to add or subtract the value of "top" in this css shift. Instead of specifying a specific number of pixels, I would like to add 20px to the current value provided by external css.

The goal is to move the list down.

$('.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>
+5
source share
6 answers

Based on your edit:

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

Or you can add 20pxeach time you use it animateas follows:

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

The property topdoes not work unless you also specify position:

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

Change positionto absoluteor relativeaccording to your needs.

: , .list top, position:relative absolute .list.

+12

.css() "+ =" "- =", .animate(). :

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

. 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');
});

+1

""

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

margin-top :

$('#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)" 
0

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

-2

All Articles