【问题标题】:Make element move and when it disappears at the end of the screen make it appear again at the beginning of the screen使元素移动,当它在屏幕末尾消失时,让它再次出现在屏幕的开头
【发布时间】:2018-04-12 21:17:21
【问题描述】:

澄清我要做什么:

我有一个固定的背景图像,当用户滚动时它应该会稍微移动,这已经在工作了。但是当图像消失时,我希望它再次出现在屏幕的开头。

图像只是一个示例,它将是一个 100% 宽的 svg,因此图像一离开就必须再次出现在屏幕上:1px。

我该怎么做?

这是我的代码

https://codepen.io/anon/pen/YaMJyG

    var offset = $("#moving-element").offset();
    $(window).scroll(function(event) {
      var st = $(this).scrollTop();
      $("#moving-element").css("left", st + offset.left);
    });
    body {
      height: 9999px
    }
    
    #moving-element {
      height: 100px;
      width: 100%;
      background:   url('https://vignette.wikia.nocookie.net/nintendo/images/5/5c/Jumping_Mario_Artwork_-_New_Super_Mario_Bros._Wii.png/revision/latest?cb=20120318204810&path-prefix=en');
     background-repeat: no-repeat;
      background-size: contain;
      background-position: bottom left;
      position: fixed;
      bottom: 0;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="moving-element">  
    </div>

【问题讨论】:

标签: javascript html css


【解决方案1】:

通过 st%width 更新变量 st ,其中 width 是 div 的宽度。因此,每当它超过 div 宽度时,它就会再次自动重置

var offset = $("#moving-element").offset();
var width = $("#moving-element").width();
$(window).scroll(function(event) {
  var st = $(this).scrollTop();
  st = st%width;
  $("#moving-element").css("left", st + offset.left);
});

【讨论】:

    猜你喜欢
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    相关资源
    最近更新 更多