使用Jquery添加内容

时间:2016-05-13 08:18:56

标签: javascript jquery html css

我在JS Fiddle中的演示https://jsfiddle.net/dineshkanivu/5fp2sjgb/2/

我想动态地将内容添加到第4行的id="myNote"。 单击按钮 lines ,可以看到总行数。我想在第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>

1 个答案:

答案 0 :(得分: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/