我有大约 33 个 div,我正在随机设置这些位置并为这些地方设置动画。这些 div 最初是在 flex
的帮助下定位的,然后通过将其位置设置为 relative
并更改 left
和 来随机化位置>顶部
值。每次点击都会发生这种情况。
每次单击时,我都希望将 div 返回到正常位置。到目前为止,我找到的唯一解决方案是 .removeAttr('style')
方法。然而,我希望能够让他们返回到原来的位置。这可能吗?
这是代码:
var position_checker = false;
$(document).click(function() {
if(position_checker == false) {
$('.poster05-text').each(function() {
var position = $(this).offset();
$(this).css({
position: 'relative',
}, position);
var docHeight = $(document).height(),
docWidth = $(document).width(),
divWidth = 500,
divHeight = 500,
heightMax = docHeight - divHeight,
widthMax = docWidth - divWidth;
var posLeft = Math.floor(Math.random() * widthMax);
var posTop = Math.floor(Math.random() * heightMax);
// console.log(docHeight, docWidth);
$(this).animate({
position: 'fixed',
left: posLeft,
top: posTop
}, 1000 , 'easeInQuint');
});
position_checker=true;
}
else if(position_checker==true) {
$('.poster05-text').each(function() {
$(this).removeAttr('style');
});
position_checker=false;
}
});
最佳答案
我不知道这是不是正确的方法..但是无论如何..你需要保存每个div之前的left
和top
位置在数组上
var position_checker = false , T_L_Positions = [];
$(document).click(function() {
if(position_checker == false) {
$('.poster05-text').each(function(i) {
var position = $(this).offset();
$(this).css({
position: 'relative',
}, position);
T_L_Positions[i] = new Array(position.top ,position.left);
var docHeight = $(document).height(),
docWidth = $(document).width(),
divWidth = 500,
divHeight = 500,
heightMax = docHeight - divHeight,
widthMax = docWidth - divWidth;
var posLeft = Math.floor(Math.random() * widthMax);
var posTop = Math.floor(Math.random() * heightMax);
// console.log(docHeight, docWidth);
$(this).animate({
position: 'fixed',
left: posLeft,
top: posTop
}, 1000 , 'easeInQuint');
});
position_checker=true;
}
else if(position_checker==true) {
$('.poster05-text').each(function(i) {
$(this).animate({
position: 'relative',
left: T_L_Positions[i][1],
top: T_L_Positions[i][0]
}, 1000 , 'easeInQuint');
});
position_checker=false;
}
});
注意: 此代码尚未测试 ..但您可以尝试一下
也许您需要将代码包装在 $(document).ready(function(){//code here })
关于javascript - jQuery:从多个 div 中动画删除样式属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49889248/