Home >Web Front-end >JS Tutorial >Three methods to determine whether the elements on the js page are within the screen display area
Application scenario: As long as the page is loaded, the li that appears in the page will output the number of the request to the console; in the page loaded this time, roll the scroll bar back to the previous li and no longer send the request to the console. The console outputs things, that is to say, the li that has been displayed will no longer output things to the console.
<body> <ul> <li onclick="jumpOther()">0001</li> <li>0002</li> <li>0003</li> <li>0004</li> <li>0005</li> <li>0006</li> <li>0007</li> <li>0008</li> <li>0009</li> <li>00010</li> <li>00011</li> <li>00012</li> <li>00013</li> <li>00014</li> <li>00015</li> <li>00016</li> <li>00017</li> <li>00018</li> <li>00019</li> <li>00020</li> <li class="ts">00021</li> <li>00022</li> </ul> </body>
defines a global variable lastItem to record the index of the last displayed li; in this way, when the index of li>lastItem, it means that the li has not been displayed yet , can output things.
<script type="text/javascript"> var lastItem=0; $(document).ready(function () { sendAsk(); window.addEventListener("scroll",function(e){ sendAsk(); }); }); function sendAsk(){ var lis= $('ul').find("li"); //swHeight=滚动的高度+窗体的高度;当li的offset高度<=swHeight,那么说明当前li显示在可视区域了 var swHeight=$(window).scrollTop()+$(window).height(); $.each(lis, function (index, item) { mTop=item.offsetTop; var dItem=index+1; if(mTop<swHeight&&dItem>lastItem){ console.log(index+1+"个发送请求 "); lastItem+=1; } }); } </script>
Dynamically add an attribute to each li to indicate whether the li has been displayed; after sending the request, set the attribute to true; if it has not been displayed, it will not Just add attributes.
function sendAsk() { var lis= $('ul').find("li"); //swHeight=滚动的高度+窗体的高度;当li的offset高度<=swHeight,那么说明当前li显示在可视区域了 var swHeight=$(window).scrollTop()+$(window).height(); $.each(lis, function (index, item) { mTop=item.offsetTop; if(mTop<swHeight&&!item.getAttribute("data-send")){ console.log(index+1+"个发送请求 "); item.setAttribute("data-send","true"); } }); }
Use the getBoundingClientRect() method, as long as .top<= the height of the visible area
function sendAsk(){ var lis= $('ul').find("li"); //swHeight=滚动的高度+窗体的高度;当li的offset高度<=swHeight,那么说明当前li显示在可视区域了 var swHeight=$(window).height(); $.each(lis, function (index, item) { mTop=item.getBoundingClientRect().top; console.log(mTop); if(mTop<=swHeight){ console.log(index+1+"个发送请求 "); } }); }
Related recommendations:
javascript full screen method of displaying page elements in full screen
Video tutorial: Website real-time stopwatch implementation in JS - 27 classic practical exercises for front-end JS development
The above is the detailed content of Three methods to determine whether the elements on the js page are within the screen display area. For more information, please follow other related articles on the PHP Chinese website!