如何使一个元素从网页的顶部跳到底部再跳回到顶部

How to make an element jump from top to the bottom of the web page and back to the top?

本文关键字:顶部 底部 何使一 元素 网页      更新时间:2023-09-26

我有一个球形状的元素div。我想做的是,当我刷新页面时,我希望球掉到网页底部,然后反弹到页面顶部。

这是我的jQuery函数,球落在网页的底部

  $(document).ready(function(){
   $("div").animate({ top: '+=585'}, 400);
});

我使用的方法正确吗?我应该使用slideWon和slideUp吗?

尝试使用jQuery UI.effect()

$(function() {
  var div = $("div");
  // `elem`: element to apply bounce effect,
  // `n`: number of bounce effects to apply to `elem`
  var bounce = function bounce(elem, n) {
    var fx = function fx(el) {
      return (el || $(this))
        .effect({
          effect: "bounce",
          easing: "swing",
          duration: 400,
          distance: window.innerHeight 
                    - (el.height() + el.offset().top * 1.5),
          direction: "down",
          times: 1
        }).promise()
    };
    return fx(elem).then.apply(elem, $.map(Array(n - 1), function() {
      return fx(elem)
    }));
  };
  
  bounce(div, 1).then(function(el) {
    // do stuff when bounce effect complete
    console.log("complete", el)
  });
});
div {
  position: relative;
  width: 100px;
  height: 100px;
  background: rgb(212, 98, 44);
  border: 2px solid navy;
  border-radius: 50%;
}
<link href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" 
rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<div></div>

利用jQuery的动画可链接性。此外,您可能不应该假设静态值585适用于每个屏幕大小。我建议使用计算值来生成偏移,检查这个fiddle:

  $(document).ready(function () {
      var viewportH = $(window).height();
      var elem = $('div');
      var elemH = elem.height();
      elem.animate({
          top: '+=' + (viewportH - elemH) // bottom of screen
      }, 400).animate({
          top: '-=' + (viewportH - elemH) // original position
      });
  });

使用此HTML:

<div id="myDiv" class="myRelativeDiv">test</div>

第一步是将div的位置设置为"相对":

.relative {
    position:relative;
}

第二步是用Jquery制作动画(你可以链接许多animate):

$(function() {
   $("#myDiv").animate({ top: '+=585'}, 400).animate({ top: '0'}, 400);
});

Js出价

$(document).ready(function(){
   $("div").animate({ top: '+=585'}, 400);
   setTimeout(
     function() 
    {
      $("div").animate({ top: '-=585'}, 400);
    }, 400);
});