使用 jquery 增加 css top 属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4359184/
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
Increment css top property using jquery
提问by ahmad
I have the following div :
我有以下 div :
<div id="new" style="position: absolute; z-index: 100; top: 210px; width: 195px..
What is the best way to increase the top
property when an event occurs?
top
事件发生时增加财产的最佳方法是什么?
Note that I've tried: $('#new').css('top')+10
but the problem is that .css
returns string.
请注意,我已经尝试过:$('#new').css('top')+10
但问题是.css
返回字符串。
回答by Steve Taylor
The simplest way is to use the +=
operator:
最简单的方法是使用+=
运算符:
$( '#new' ).css( 'top', '+=10px' );
回答by PleaseStand
You can use the parseFloat
functionto get only the initial numeric part and convert it from a string to a number. For example:
您可以使用该parseFloat
函数仅获取初始数字部分并将其从字符串转换为数字。例如:
var n = $('#new');
n.css('top', (parseFloat(n.css('top')) + 10) + 'px');
As a side note, if you want to change multiple elements' positions all at once, that could be:
作为旁注,如果您想一次更改多个元素的位置,则可能是:
$('.someClass').css('top', function(i, v) {
return (parseFloat(v) + 10) + 'px';
});
But if you are just trying to animate an element over time, take a look at jQuery's .animate
method.
但是,如果您只是想随着时间的推移对元素进行动画处理,请查看 jQuery 的.animate
方法。
回答by Quentin
var el = $('#new');
el.css('top', (parseInt(el.css('top'), 10) + 10) + 'px');
回答by tpow
I would say create a variable, increment the variable, and then reset the property using the new value, like this
我会说创建一个变量,增加变量,然后使用新值重置属性,就像这样
var topProperty = 0; //You can also populate this variable with the current value.
then in your click event
然后在你的点击事件中
{
topProperty += 10;
$('#new').css('top', topProperty + 'px');
}
回答by RobertPitt
var New = $("#new");
function onEvent()
{
New.css("top", parseFloat(New.css("top")) + 10 + "px");
}
by adding the seconds parameter of to css your setting the property.
通过在 css 中添加 seconds 参数来设置属性。