JQUERY onClick change 'top' attribute
I am trying to create a vertical scroller using jquery开发者_JS百科 and I am having troubles with my code..
function scrolldown() {
var newtop = $('.scroll-content').css('top') + '250';
$('.scroll-content').css({top: newtop});
}
The css:
.scroll-content {position:absolute; top:0px}
No problems with CSS I can change values in firebug and works fine, but the code is the issue. I want it to add 250px to current value but it doesnt work and when using .html(newtop)
i can see that the output for the "top" value is 0px250… any ideas what I am doing wrong?
$('.scroll-content').css('top')
will return something like "123px", which is a string (due to the "px"). If you add "250", you have "123px250", which is not what you want...
Try this one instead:
var newtop = $('.scroll-content').position().top + 250;
$('.scroll-content').css('top', newtop + 'px');
You need to convert the css string ('0px') into an int (0) so you can add 250, then add the 'px' again
function scrolldown() {
var newtop = parseInt($('.scroll-content').css('top')) + 250;
$('.scroll-content').css({top: newtop+'px'});
}
As an alternative to the posted answers, you can use a +=
shortcut via .animate()
with no duration, like this:
$(".scroll-content").animate({ top: "+=250px" }, 0);
This will make the change adding 250px instantly. If you actually wanted it animated, just change that 0
to a 400
for example, to get a 400ms duration.
Make sure that you are adding an integer to your top value not a string. see below:
var newtop = $('.scroll-content').css('top') + 250;
$('.scroll-content').css({top: newtop}); }
精彩评论