简体   繁体   English

使用 Javascript 计算 HTML 中的行数

[英]Count lines in HTML with Javascript

I need a way to count lines in the html so I can do logic for a business requirement.我需要一种方法来计算 html 中的行数,以便我可以为业务需求做逻辑。

I use Bootstrap + AngularJS but the solution could be in plain Javascript.我使用 Bootstrap + AngularJS,但解决方案可能是纯 Javascript。

I have no idea where to start.我不知道从哪里开始。 Any help?有什么帮助吗?

 .myClass { word-break: break-all; white-space: pre-line; }
 <div style="max-width: 50px"> <span class="myClass">aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</span> </div> <span>Total Lines: <b id="totalLines"></b></span>

I also would need a way to calculate this everytime the user makes the window smaller/bigger because of the responsive aspect.由于响应方面的原因,每次用户使窗口变小/变大时,我还需要一种计算方法。

getClientRects will be useful here getClientRects 在这里很有用

The getClientRects() method of the Element interface returns a collection of DOMRect objects that indicate the bounding rectangles for each CSS border box in a client. Element 接口的 getClientRects() 方法返回一组 DOMRect 对象,这些对象指示客户端中每个 CSS 边框的边界矩形。

 $("#totalLines").text($(".myClass")[0].getClientRects().length); console.log($(".myClass")[0].getClientRects().length); $(document).ready(function() { $(window).resize(function() { console.log("Resize event fired"); $("#totalLines").text($(".myClass")[0].getClientRects().length); }); });
 .myClass { word-break: break-all; white-space: pre-line; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div style="max-width: 500px"> <span class="myClass">aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</span> </div> <span>Total Lines: <b id="totalLines"></b></span>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM