欢迎来到代码驿站!

当前位置:首页 >

用原生js统计文本行数的简单示例

时间:2020-01-16 14:35:39|栏目:|点击:
window.getComputedStyle()

要使用原生 JavaScript 代码获取一个元素的各个 style 属性,使用 window.getComputedStyle() 是必然的。它可以返回一个 HTML 元素在浏览器中真正显示时的各个样式——当然,有些样式会被浏览器给屏蔽,比如,你要获取一个链接的颜色,并准备通过颜色来判断用户是否访问过某个地址,那肯定是不行的。

该方法返回的,是一个样式键值对,是 CSSStyleDeclaration 的实例。各属性索引名没有 - ,且采用驼峰命名法。比如 lineHeight 。

行数 = 整体高度 / 行高

整体高度通过 height 可以获取。行高可以通过 lineHeight 获取,将其结果再取整即可得到行数。

但有个问题,如果没有针对一个元素设置 line-height 值,则其默认值为 normal ,这个值在桌面浏览器中通常是 1.2 ,但还与字体有关。因此,最好是对需要计算行数的元素设置一下 line-height 值。

一个简单的实现如下:

function countLines(ele) {
 var styles = window.getComputedStyle(ele, null);
 var lh = parseInt(styles.lineHeight, 10);
 var h = parseInt(styles.height, 10);
 var lc = Math.round(h / lh);
 console.log('line count:', lc, 'line-height:', lh, 'height:', h);
 return lc;
}
完整代码示例:
<!DOCTYPE html>
<html>
<head>
 <title>Line Count</title>
 <style type="text/css">
  p {
   line-height: 1.3em;
  }
 </style>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312"></head>
<body>
<p id="target">She just made having a baby look lovely. Everything is white and she always has a fresh blueberry pie that's steaming and scones and clotted cream and she's reading The Old Man and the Sea and her little boy is rolly with bonnets. It's amazing, and I thought this is lovely. My kid is like playing with like explosive devices. I don't know where she's found them, like sticking them in our dog's ear. She already knows how to dry wall cause she puts holes in the wall.<br />
“今天的中国人一如当年的德国人,沉迷于‘崛起'幻觉,习惯于听信他人的吹捧,还想当然地认为只要中国继续保持经济增长,不仅未来的经济总量超越‘世界老大'美国可以期待,中国实现全面复兴也将是囊中之物。”上海外国语大学国际关系与公共事务学院教授程亚文在其新著《大国战略力》中尖锐地指出中国现下有不少人陷入了“盛世”幻觉,并没有意识到在经济总量的背后,中国其实还是一个极为落后的国家。世界上还没有一个大国是在风平浪静中兴起的,中国的新一轮文明复兴也将充满风险和曲折。防止国家崩溃、解体或衰败应该成为中国国家战略的重中之重。染上“软乎乎的幸福主义”只会让一个国家变得脆弱。
</p>
<p>行数:<span id="shower"></span></p>
改变窗口大小,自动计算
<button onclick="countLines()">立刻计算</button>
 
<script type="text/javascript">
var target = document.getElementById('target');
var shower = document.getElementById('shower');
 
function countLines(ele) {
 var styles = window.getComputedStyle(ele, null);
 var lh = parseInt(styles.lineHeight, 10);
 var h = parseInt(styles.height, 10);
 var lc = Math.round(h / lh);
 console.log('line count:', lc, 'line-height:', lh, 'height:', h);
 return lc;
}
 
function change() {
 shower.innerHTML = countLines(target);
}
window.onresize = change;
change();
</script>
</body>
</html>

上一篇:PHP获取MySQL插入数据的自增主键

栏    目:

下一篇:R语言ggplot2边框背景去除的实现

本文标题:用原生js统计文本行数的简单示例

本文地址:http://www.codeinn.net/misctech/2200.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有