滚动时淡化图像

Fade image on scrolling

我正在尝试使用以下代码在滚动时淡化图像:

html:

<img th:src="@{/img/bc.jpg}" class="top" onscroll="myFunction()"/>

css:

.top {
    margin: 0;
    width: 100%;
    height: 100%;
    opacity: 1;
}

js:

<script 
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">

function myFunction() {
var myElement = $('.top');

$(window).on('scroll', function () {
    var st = $(this).scrollTop();
    myElement.css({
        'opacity': 1 - st / 600
    });
});
}

</script>

它不会工作,因为这是我第一次使用 JQuery,我认为问题可能是导入方面的?我试图在不将 js 代码也放入函数中的情况下执行此操作,但没有成功。

首先你不需要在html(inline)

中指定滚动函数
<img th:src="@{/img/bc.jpg}" class="top"/>

其次,您的执行代码应该在 jQuery

$(document).ready 事件中
<script 
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">

<script>
    $(document).ready(function() {
       var myElement = $('.top');
       $(window).on('scroll', function () {
         var st = $(this).scrollTop();
         myElement.css({
            'opacity': 1 - st / 600
         });
      });
    });
</script>

JSFiddle demo link

应该可行

你的期望对我来说还不够明确,请在下面检查我的概念。当 window 向下滚动时,我们会检测到如果从顶部滚动 space 大于 100px,则图像将淡出(隐藏),相反滚动,图像将淡入(显示) .您可以将其用作简单代码。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
  <script type="text/javascript">
    $(function(){
      var element = $('.top');
      $(window).scroll(function () {
        if ($(this).scrollTop() > 100) {
          element.fadeIn();
        }
        else {
          element.fadeOut();
        }
       });
    });
</script>
<img th:src="@{/img/bc.jpg}" class="top"/>