我试图在外汇中增加当前“top”属性值的值。
http://jsfiddle.net/fqmnksgL/
var percent = 50;
$('div').forEach(function (obj, i) {
$(obj).css('top', $(obj).css('top') + percent);
});
上面的代码有什么问题吗?
发布于 2015-04-16 06:55:00
你可以试试
var percent = 50;
$('div').css('top', function(i, obj) {
return i * percent;
});
div {
width: 50px;
height: 50px;
background: red;
position: absolute;
top: 10px;
left: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
发布于 2015-04-16 06:28:12
forEach
是Array
的一部分。使用each
代替。可以使用函数回调来增加当前元素的top
属性。
var percent = 50;
$('div').each(function() {
$(this).css('top', function(_, top){
return parseInt(top, 10) + percent;
});
});
但这不像你想的那样有效。也许您应该尝试使用$.fn.prev
的另一个答案
发布于 2015-04-16 06:34:06
您不能将百分比(%)添加到px值中,您需要转换其中的一个
var px = 50;
$('div').each(function () {
$(this).css('top', parseInt($(this).prev().css('top')) + px);
});
http://jsfiddle.net/fqmnksgL/6/
https://stackoverflow.com/questions/29666859
复制相似问题