滚动时淡出图像

时间:2018-01-11 08:09:10

标签: javascript jquery html fade

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

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代码放在函数中,并且它没有用。

2 个答案:

答案 0 :(得分:2)

首先,您不需要在html(内联)中指定滚动功能

<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

那应该有用

答案 1 :(得分:1)

Your expectation is not clear enough for me, please check my concept below. When window is scroll down, we will detect that if scroll space from top is bigger than 100px, the image will be faded out (hide) and as opposite scroll the image will be faded in (show). You can use it as simple codes.

<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"/>