zoukankan      html  css  js  c++  java
  • [麦先生]如何使用AJAX实现按需加载

     按需加载的优势:在实际调查中发现,很多的网民在游览网站时具有明确的指向性,往往在进入主页后直接搜索进入自己需要的商品列表内,如果在客户进入主页时将主页信息全部加载完毕后展示给顾客,会极大的浪费网站资源,同时也会降低客户体验度,因而按需加载则成为了当今网站构建的主流;

    <!DOCTYPE html>

    <html lang="en">

    <head>

    <meta charset="UTF-8">

    <title>按需加载图片</title>

    <style type="text/css">

    *{margin:0px;padding:0px;list-style:none;}

    ul{

    height:auto;

    overflow:hidden;

    400px;

    margin:0 auto;

    }

    li{

    300px;

    height:200px;

    border:solid 1px #ddd;

    overflow:hidden;

    }

    </style>

    </head>

    <body>

    <ul>

    <li><img data-src="./sunli/1.jpg" alt="" width="100%"></li>

    <li><img data-src="./sunli/2.jpg" alt="" width="100%"></li>

    <li><img data-src="./sunli/3.jpg" alt="" width="100%"></li>

    <li><img data-src="./sunli/4.jpg" alt="" width="100%"></li>

    <li><img data-src="./sunli/5.jpg" alt="" width="100%"></li>

    <li url="./rexiao.php">

    </li>

    </ul>

    <script type="text/javascript" src="jquery-1.8.3.min.js"></script>

    <script type="text/javascript">

    //绑定窗口的滚动事件

    $(window).scroll(function(){

    //遍历检测里面的元素尺寸

    $('li[isLoaded!=1]').each(function(){

    //获取滚动高度

    var sT = $(window).scrollTop();

    //获取窗口的可视区域的高度

    var cT = $(window).height();

    //获取元素距离文档顶部的偏移量

    var t = $(this).offset().top;

    //暂存当前元素对象

    var curLi = $(this);

    //检测判断

    if(t <= sT + cT){

    //检测是否具有url属性

    var url = $(this).attr('url');

    //如果有  发送ajax 获取请求之后的数据

    if(url){

    //发送ajax

    $.get('rexiao.php',{}, function(data){

    curLi.html(data);

    return;

    })

    }

    //这个时候要显示了 修改元素的src属性 

    var src = $(this).find('img').attr('data-src');

    //设置

    $(this).find('img').attr('src',src);

    //做标识

    $(this).attr('isLoaded','1');

    }

    })

    })

    //使用代码来触发滚动事件  

    $(window).trigger('scroll');

    </script>

    </body>

    </html>

  • 相关阅读:
    Balance的数学思想构造辅助函数
    1663. Smallest String With A Given Numeric Value (M)
    1680. Concatenation of Consecutive Binary Numbers (M)
    1631. Path With Minimum Effort (M)
    1437. Check If All 1's Are at Least Length K Places Away (E)
    1329. Sort the Matrix Diagonally (M)
    1657. Determine if Two Strings Are Close (M)
    1673. Find the Most Competitive Subsequence (M)
    1641. Count Sorted Vowel Strings (M)
    1679. Max Number of K-Sum Pairs (M)
  • 原文地址:https://www.cnblogs.com/maixiansheng/p/5484295.html
Copyright © 2011-2022 走看看