javascript - 将顺序行编号应用于段落 : is it possible? 中的行

标签 javascript jquery

是否可以让 jquery/javascript 在段落中所有行的开头插入顺序行号,并且更好的是,按照顺序插入后续段落?

我希望能够快速向学生推荐文章的特定行(在类环境中)。我有很多文章想要应用此功能,每篇文章都有不同数量的段落。

我希望这可能是可能的,即使是在响应式页面中,段落的宽度会根据显示设备而变化,因此每个段落中的行数会变多或变少。

在此先感谢任何可以提供帮助的人。

最佳答案

这是一种可能适合您目的的方法。

  1. 获取单行段落的高度,供引用。
  2. 对于每个段落,获取实际高度,并推断行数。
  3. 遍历行并在绝对位置添加编号。

var refHeight = $("p").eq(0).height();
$("p").eq(0).remove();
var cnt = 1;
$("p").each(function(index) {
    var pos = $(this).position();
    var h = $(this).height();
    var lines = h / refHeight;
    var lineHeight = h / lines;
    for (var i=pos.top ; i<pos.top+h ; i += lineHeight) {
        var num = $("<p>", { class: "number" });
        num.text(cnt++);
        num.css("top", i);
        $(this).before(num);
        console.log(i);
    }
});

(Fiddle)


编辑

如果您想使用固定的行长(以便每个人看到相同的数字),您可以将上面的内容与以下内容结合起来:

  1. 将段落分成几行。
  2. 将每一行包裹在一个 span/div 中,然后重新追加。
  3. Block the browser from text wrapping .

$("p").each(function() {
    var text = $(this).text();
    $(this).html("");
    var i=0;
    while (i<text.length) {
        lineCharWidth = charWidth;
        while (i+lineCharWidth < text.length && text[i+lineCharWidth] != ' ') {
            lineCharWidth++;
        }
        var line = $("<span>", { class: "line" }).text(text.substr(i, lineCharWidth));
        $(this).append(line).append("<br/>");
        i += lineCharWidth;
    }
});

(Fiddle)

关于javascript - 将顺序行编号应用于段落 : is it possible? 中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19391159/

相关文章:

javascript - 淡入jquery div显示

javascript - 在 JS 中动态设置 div 位置和大小 - 如何使过渡更平滑?

javascript - CSS Transform Math - 计算倾斜引起的div的高度

jQuery: "Doesn' t 有“选择器?

javascript - Bootstrap 因错误行为而崩溃

java - 使用struts和ibatis的通用报告框架

javascript - 我的 Bootstrap 导航栏未显示在移动设备上

javascript - 尝试安装 vue/cli 时权限被拒绝

javascript - Jasmine:TypeError - Binary8 不是构造函数

javascript - 在 mousedown/touchstart 上获取相对于父对象而不是视口(viewport)的位置