2016-05-13 84 views
1

我演示在JS小提琴https://jsfiddle.net/dineshkanivu/5fp2sjgb/2/添加内容使用jQuery

我想在第4行动态添加内容到id="myNote"。 点击按钮,你可以看到总的行数。我想在第4行之后添加一些html内容。我怎样才能做到这一点使用jQuery

段:

$(function() { 
 
    $("#getLines").click(function() { 
 

 
    var myheight = $("#myNote").height(); 
 
    parseFloat($("#myNote").css("line-height")); 
 
    //$('#myNote').after('<button>button</button>'); 
 
    alert(myheight); 
 

 
    }); 
 
});
#myNote { 
 
    width: 300px; 
 
    line-height: 1; 
 
    height: auto; 
 
    text-align: justify; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="myNote"> 
 
    Finally, designing the last sentence in this way has the added benefit of seamlessly moving the reader to the first paragraph of the body of the paper. In this way we can see that the basic introduction does not need to be much more than three or four 
 
    sentences in length. If yours is much longer you might want to consider editing it down a bit! Here, by way of example, is an introductory paragraph to an essay in response to the following question: 
 
</div> 
 

 
<button id="getLines">lines</button>

+2

这将是令人难以置信* *难以实现。您需要以某种方式计算第5行的第一个字符,然后插入之前所需的内容。 –

+1

作为与@RoryMcCrossan相关的备忘录,您需要自己尝试一下,当您遇到特定问题时,请向我们提供一个重现问题的实例。祝你好运。 –

+1

我觉得这个片段有点不对,它显示的是156行?当你计算行数时,它只有10 – guradio

回答

3

根据这一post我写了一个小功能来做到这一点。 当然有一个更有效的方法。但它工作正常。

我将自己的每个单词都包裹在自己的范围内。之后,我检查所有跨度的位置,获取行号,并将该行号添加到跨度。

function insertTextAtLine(target,lineNumber,textInsert){ 

var words = target.text().split(' '); 
var text = ''; 
$.each(words, function(i, w){ 
       if($.trim(w)) text = text + '<span>' + w + '</span> '; 
}); 

target.html(text); 
var line = 0; 
var prevTop = - parseFloat($("#myNote").css("line-height")); 
$('span', target).each(function(){ 
    var word = $(this); 
    var top = word.offset().top; 
    if(top != prevTop){ 
    prevTop = top; 
    line++; 
    } 
    word.attr('class', 'line' + line); 

}); 
var insert=$('<span />').text(textInsert); 
target.find('.line'+lineNumber).first().prepend(insert); 
}; 

小提琴:https://jsfiddle.net/tye3czva/4/

+0

非常感谢亲爱的.................... .............. –

+0

如果您有任何其他答案,欢迎!!!!! –