jQuery Waypoints fires on page load when images are display block

血红的双手。 提交于 2020-01-15 05:11:47

问题


Im using the jQuery waypoints plugin. This following is working fine except on page load the console message is fired before ive scrolled. This stops If I remove the display block being applied to the images, but I need this for my site to work.

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
        <script src="js/jquery-2.0.3.js"></script>
        <script src="js/waypoints.js"></script>
        <style>
            body {
                margin: 0;
                padding: 0;
            }
            img {
                max-width: 100%;
                display: block;
                margin: auto;
            }
            #img3 {
                opacity: 0.5;
            }

        </style>
        <script>
            $(document).ready(function() {
                $('#img3').waypoint(function() {
                  console.log('Basic example callback triggered.');
                });
            });
        </script>
    <body>
        <img src="images/1.jpg" alt="image 1" id="img1">
        <img src="images/2.jpg" alt="image 2" id="img2">
        <img src="images/3.jpg" alt="image 3" id="img3">
        <img src="images/4.jpg" alt="image 4" id="img4">
    </body>
</html>

回答1:


Your images do not have width/height until they start loading. You are instantiating the waypoint during the domready event, before your images start loading. At that time, because they do not have width/height, all your images live at the y coordinate of 0 on the page, and that's where the waypoint triggers. You can solve this at least two ways:

  • Give your images a width+height in your HTML.
  • Create the waypoint within a $(window).load handler, which will wait until all images are finished loading.

The reason this was not happening when the images are inline is that the 0x0 img element lives within the line-height text box of body, so the img lives some small number of pixels from the top instead of the exact top.



来源:https://stackoverflow.com/questions/18104033/jquery-waypoints-fires-on-page-load-when-images-are-display-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!