在div边框内部动画图片

5

我想要制作一个动画,让图片在一个div容器的边界内随机移动。我在这里找到了一些设置动画边框的解决方案,但是没有一个能让图片保持在div内。

这里有一个示例代码 - 我需要让红色正方形在黄色div内移动,即使我向下滚动页面。

我该如何实现呢?

$(document).ready(function() {
    animateDiv();

});

function makeNewPosition($container) {

    // Get viewport dimensions (remove the dimension of the div)
    $container = ($container || $(window))
    var h = $container.height() - 50;
    var w = $container.width() - 50;

    var nh = Math.floor(Math.random() * h);
    var nw = Math.floor(Math.random() * w);

    return [nh, nw];

}

function animateDiv() {
    var $target = $('.a');
    var newq = makeNewPosition($target.parent());
    var oldq = $target.offset();
    var speed = calcSpeed([oldq.top, oldq.left], newq);

    $('.a').animate({
        top: newq[0],
        left: newq[1]
    }, speed, function() {
        animateDiv();
    });

};

function calcSpeed(prev, next) {

    var x = Math.abs(prev[1] - next[1]);
    var y = Math.abs(prev[0] - next[0]);

    var greatest = x > y ? x : y;

    var speedModifier = 0.1;

    var speed = Math.ceil(greatest / speedModifier);

    return speed;

}
div#container {height:100px;width:100px;margin-left: 500px;background-color: yellow;}

div.a {
width: 50px;
height:50px;
 background-color:red;
position:absolute;
    
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h1>TITLE!</h1>
<p>
Just some test which the red squere won't touch at any point
</p>
</div>
<div id="container">
<div class='a'></div>
</div>

3个回答

3
当你给一个元素设置position:absolute;属性时,你必须定义一个带有position:relative;属性的父元素,以保证子元素(绝对定位元素)不会超出其边界。

$(document).ready(function() {
    animateDiv();

});

function makeNewPosition($container) {

    // Get viewport dimensions (remove the dimension of the div)
    $container = ($container || $(window))
    var h = $container.height() - 50;
    var w = $container.width() - 50;

    var nh = Math.floor(Math.random() * h);
    var nw = Math.floor(Math.random() * w);

    return [nh, nw];

}

function animateDiv() {
    var $target = $('.a');
    var newq = makeNewPosition($target.parent());
    var oldq = $target.offset();
    var speed = calcSpeed([oldq.top, oldq.left], newq);

    $('.a').animate({
        top: newq[0],
        left: newq[1]
    }, speed, function() {
        animateDiv();
    });

};

function calcSpeed(prev, next) {

    var x = Math.abs(prev[1] - next[1]);
    var y = Math.abs(prev[0] - next[0]);

    var greatest = x > y ? x : y;

    var speedModifier = 0.1;

    var speed = Math.ceil(greatest / speedModifier);

    return speed;

}
div#container {
  height:100px;
  width:100px;
  margin-left: 500px;
  background-color: yellow; 
  position:relative;/*Added position to the parent container*/
}

div.a {
 width: 50px;
 height:50px;
 background-color:red;
 position:absolute;
    
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h1>TITLE!</h1>
<p>
Just some test which the red squere won't touch at any point
</p>
</div>
<div id="container">
<div class='a'></div>
</div>

参考链接1: https://css-tricks.com/absolute-relative-fixed-positioining-how-do-they-differ/

在线演示: https://www.w3schools.com/css/tryit.asp?filename=trycss_position_absolute


请不要使用w3school作为参考,请将以下与编程相关的内容从英文翻译成中文。只返回翻译后的文本: - Temani Afif
1
因为我们应该考虑准确的参考和官方的,w3school并不是官方参考,而且那里有很多错误。最好依赖于https://developer.mozilla.org/en-US/docs/Web或使用规范https://www.w3.org/。 - Temani Afif
明白,先生! - Viira
1
谢谢!感谢提供参考和代码片段! - Yakir Mordehay

0

$(document).ready(function() {
    animateDiv();

});

function makeNewPosition($container) {

    // Get viewport dimensions (remove the dimension of the div)
    $container = ($container || $(window))
    var h = $container.height() - 50;
    var w = $container.width() - 50;

    var nh = Math.floor(Math.random() * h);
    var nw = Math.floor(Math.random() * w);

    return [nh, nw];

}

function animateDiv() {
    var $target = $('.a');
    var newq = makeNewPosition($target.parent());
    var oldq = $target.offset();
    var speed = calcSpeed([oldq.top, oldq.left], newq);

    $('.a').animate({
        top: newq[0],
        left: newq[1]
    }, speed, function() {
        animateDiv();
    });

};

function calcSpeed(prev, next) {

    var x = Math.abs(prev[1] - next[1]);
    var y = Math.abs(prev[0] - next[0]);

    var greatest = x > y ? x : y;

    var speedModifier = 0.1;

    var speed = Math.ceil(greatest / speedModifier);

    return speed;

}
div#container {
position:relative;
  height:100px;width:100px;margin-left: 500px;background-color: yellow;}

div.a {
 width: 50px;
 height:50px;
 background-color:red;
 position:absolute;
    
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h1>TITLE!</h1>
<p>
Just some test which the red squere won't touch at any point
</p>
</div>
<div id="container">
<div class='a'></div>
</div>


2
请在您的答案中添加解释。 - לבני מלכה

0

我正在使用CSS动画使其看起来更加流畅。更改已记录在Javascript/jQuery和CSS源代码中。

CSS动画比jQuery animate快得多,因为它们可以在单独的线程上运行。

$(document).ready(function() {
  /* Initiate animation */
  animateDiv();
    
  /* Apply animation class */
  $(".a").addClass("animate");
});

/* Trigger the end of the transition */
$("div.a").on('transitionend', function() {
  /* Run next animation when previous one stopped */
  animateDiv();
});

function makeNewPosition($container) {
  // Get viewport dimensions (remove the dimension of the div)
  $container = ($container || $(window))
  var h = $container.height() - 50;
  var w = $container.width() - 50;
  var nh = Math.floor(Math.random() * h);
  var nw = Math.floor(Math.random() * w);
  return [nh, nw];
}

function animateDiv() {
  var $target = $('.a');
  var newq = makeNewPosition($target.parent());
  var oldq = $target.offset();
  /* Calculate duration in ms */
  var speed = calcSpeed([oldq.top, oldq.left], newq) + "ms";
  
  /* Set the duration of the animation */
  $(".a.animate").css("transitionDuration", speed);

  /* Set the new coordinates */
  $(".a").css({"top":newq[0], "left":newq[1]});
  
  /*
  $('.a').animate({
    top: newq[0],
    left: newq[1]
  }, speed, function() {
    animateDiv();
  });
  */
};

function calcSpeed(prev, next) {
  var x = Math.abs(prev[1] - next[1]);
  var y = Math.abs(prev[0] - next[0]);
  var greatest = x > y ? x : y;
  var speedModifier = 0.1;
  var speed = Math.ceil(greatest / speedModifier);
  return speed;
}
div#container {
  height: 100px;
  width: 100px;
  margin-left: 500px;
  background-color: yellow;
  position: relative; /* Added */
}

div.a {
  width: 50px;
  height: 50px;
  background-color: red;
  position: absolute;
  top: 0; /* Initial position */
  left: 0; /* Initial position */
}

div.a.animate {
  transition: left, top;
  transition-duration: 1000ms; /* Default value */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <h1>TITLE!</h1>
  <p>
    Just some test which the red squere won't touch at any point
  </p>
</div>
<div id="container">
  <div class='a'></div>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接