JQUERY onClick 更改“顶部”属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3339046/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:16:08  来源:igfitidea点击:

JQUERY onClick change 'top' attribute

jquerycss

提问by Matthew Pateman

I am trying to create a vertical scroller using jquery and I am having troubles with my code..

我正在尝试使用 jquery 创建一个垂直滚动条,但我的代码遇到了问题..

function scrolldown() {     
    var newtop = $('.scroll-content').css('top') + '250';   
    $('.scroll-content').css({top: newtop});
}

The css:

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?

CSS 没有问题我可以更改 firebug 中的值并且工作正常,但代码是问题所在。我希望它将 250px 添加到当前值,但它不起作用,使用时.html(newtop)我可以看到“顶部”值的输出为 0px250 ......任何想法我做错了什么?

回答by opatut

$('.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...

将返回类似“123px”的内容,它是一个字符串(由于“px”)。如果添加“250”,则会得到“123px250”,这不是您想要的...

Try this one instead:

试试这个:

var newtop = $('.scroll-content').position().top + 250;
$('.scroll-content').css('top', newtop + 'px');

回答by Ties

You need to convert the css string ('0px') into an int (0) so you can add 250, then add the 'px' again

您需要将 css 字符串 ('0px') 转换为 int (0),以便添加 250,然后再次添加 'px'

function scrolldown() {
  var newtop = parseInt($('.scroll-content').css('top')) + 250;
  $('.scroll-content').css({top: newtop+'px'});
}

回答by Nick Craver

As an alternative to the posted answers, you can use a +=shortcut via .animate()with no duration, like this:

作为已发布答案的替代方案,您可以使用无持续时间的+=快捷方式.animate(),如下所示:

$(".scroll-content").animate({ top: "+=250px" }, 0);?

This will make the change adding 250px instantly. If you actually wanted it animated, just change that 0to a 400for example, to get a 400ms duration.

这将使更改立即增加 250px。如果你真的想它的动画,只是改变是0一个400例如,要获得400毫秒时间。

回答by nicholasklick

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