English 中文(简体)
Javascrapty - 获得一行最后单词
原标题:Javascript - Getting the last word in a line

以下是一个例子:

<div><span style="font-size:15px;">some text here which is </span>
<span style="color:red;">split automatically by the browser.</span></div>

浏览器将它变成(带有自然样式的) :

some text here which is split
automatically by the browser.

我正在建立一个 javascript 应用程序, 该应用程序需要理解每行中的最后单词( 在此情况下为 < code> split ) 。 目前我正在使用 CSS < code > white- space 属性来处理溢出文本 。 因此, 浏览器不会给我关于它会在哪里打破线条的线索 。 因此, 要理解每行中的最后单词有什么好的功能?

<强 > EDIT

我正在使用纯javascript, 所以jQuery 不是一个选项, 且 < code> 白空 属性被应用到 < code> div 上。 因此, 实际上, 请将 < code > div 视为直线转换器 。

最佳回答

您可以逐字重写整个句子, 记录高度变化。 以下通过代码解释 :

HTML :

<div id="flop" class="foobar">Lorem ipsum dolor sit amet, consectetur adipisicing 
elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim 
ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea 
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit 
esse cillum dolore eu fugiat nulla pariatur.</div>
<br>
<button value="Go" onclick="foo();">Go</button>​​​​​​​​​​​​​​​​​​​​​​​​​​​​

脚本 :

function foo(){
    var d = document.getElementById( flop );
    var t = d.innerHTML;
    var w = t.split(   );       

    d.innerHTML = w[0];
    var height = d.clientHeight;
    for(var i = 1; i < w.length; i++){
        d.innerHTML = d.innerHTML +     + w[i];

        if(d.clientHeight > height){
            height = d.clientHeight;
            console.log(w[i-1]);
        }
    }
}

这将将每一行的最后单词记录到控制台, 除了最后一行。 我留给您。 这个解决方案的好东西是, 即使在窗口调整大小后, 它仍然正常工作 。

顺便说一句,

问题回答

暂无回答




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.