javascript - jQuery:从多个 div 中动画删除样式属性

标签 javascript jquery html css

我有大约 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之前的lefttop位置在数组上

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/

相关文章:

javascript - 使用相同的 jQuery 函数但在 HTML 中导致冲突

JavaScript 帮助 - JQuery 未定义

Jquery 多选值不是 UTF-8

javascript - 使用 ng-if 的多个元素总是只显示其中 1 个,它们可以共享相同的 id 吗?

php - 如何在 PHP 中复制 SQL 结果变量?

javascript - 将文件对象转换为 <img> Angular

jQuery ReplaceWith() 之后 JavaScript 断开连接

javascript - Prefer destructuring es-lint错误

PHP - 仅在主页上隐藏元素 - WordPress 网站

javascript - 如何用html5 canvas元素绘制透明图片