首页 > 解决方案 > Changing Image position when scrolling page

问题描述

I'm new to javascript and wanna create a HTML page and would like to make an image like floating on my page and it will interacting when user scrolling up and down of the website but I just couldn't figure it out. Anyone has idea how to deal with it?

            <script>


            $(window).scroll(function () { 
                //You've scrolled this much:
                // $('p').text("You've scrolled " + $(window).scrollTop() + " pixels");
                var doc = doc
                var x = document.getElementsByClassName("ImageTesting");
                //x.style.top =  "$(window).scrollTop()";
                x.css({'top': $(window).scrollTop() +'px'});

                console.log($(window).scrollTop() + "px")
                //console.log(x.style.top)
            });



            </script>

标签: javascriptjquerycss

解决方案


您可以使用上面首先提到的简单 CSS 属性来做到这一点 带有图像标签的 CSS Sticky 属性或只是

<div class="bgFloat"></div>
<style> 
  .bgFloat {
    background-image: url(image.jpg);
    background-attachment: fixed;
    background-position: center;
    background-size: contain;
    background-repeat: no-repeat;
  }
</style>

它将帮助您将图像位置固定为背景。或者,如果您想继续使用图像标签,请按照 'position:sticky; top:0' 或您想要放置元素的任何位置。


推荐阅读