jquery根据不同分辨率以及浏览器缩放动态展示内容数量

50 阅读1分钟

最近项目中提到一个框子里不希望出现滚动条,展示的条数呢也要根据不同分辨率展示不同的条数,并且在浏览器缩放时候条数依旧跟着变,因为项目是用的还是jquery,所以就用jquery实现了这个需求,话不多说,搞!!!

首先是html以及一些小样式代码
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>案例</title>
    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    <style>
      html,
      body {
        height: 98%;
      }
      .outer {
        width: 150px;
        height: 50%;
        border: 1px #666 solid;
        background: #fff;
        padding:0 10px;
        overflow: hidden;
        list-style: none;
      }
      .outer li {
        width: 100%;
        height: 25px;
        line-height: 25px;
      }
    </style>
  </head>
  <body>
    <ul class="outer"></ul>
  </body>
  </html>
接下来是js部分啦,有些动态获取的数据的需求我没写,基本上封装一套放进去就可以了
 <script>
    let num = countNum()
    // 渲染数据
    let html = '';
    for (let i = 0; i < num; i++) {
      html += `<li>我是第${i + 1}个li标签</li>`;
    }
    $('.outer').html(html);
    countNum()
    // 缩放动态控制已有数量,如果想动态调用接口,则在事件中写相关逻辑,但是不建议,因为缩放会导致频繁调用接口
    $(window).resize(() => {
      let num = countNum()
      $('li').each((e) => {
        if (e > num - 1) {
          $('li').eq(e).hide();
        } else {
          $('li').eq(e).show();
        }
        countNum()
      });
    });
    // 数量计算
    function countNum() {
      // 获取容器高度
      let outHeight = $('.outer').height();
      // 计算可展示数量,这里将每个高度定为25
      let num = parseInt(outHeight / 25);
      // li总高度
      let liHeight = $('li').height() * num;
      // 计算留白
      let leaveWhite = (outHeight - liHeight) / num;
      // 留白均分
      $('li').css({ 'margin-top': leaveWhite + 'px' });
      return num
    }
  </script>