2012-05-24 26 views
3

下面是一個例子:使用Javascript - 獲取最後一個字線

<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應用必須理解每行中的最後一個單詞(在這種情況下爲split)。目前我正在使用CSS white-space屬性來處理溢出文本。因此,瀏覽器不會給我一個關於它在哪裏斷線的線索。那麼,理解每一行中最後一個單詞的功能是什麼?

編輯

我使用純JavaScript,因此jQuery的不會是一個選項和white-space屬性應用到div。所以實際上,將div想象爲線渲染器。

+0

是否總是被span包裹的線?是jQuery的選項或只是普通的JS? – Joseph

+1

@JosephtheDreamer,我已經更新了這個問題。 –

+0

http://msackoverflow.com/questions/5673752/searching-for-a-last-word-in-javascript – msanford

回答

1

您可以逐字改寫整個句子,記錄高度變化。以下是通過代碼一些解釋:

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]); 
     } 
    } 
} 

這將記錄每行控制檯的最後一句話,除了最後一行。我把它留給你。這個解決方案的好處在於,即使在窗口大小調整後,它也能正常工作。

順便說一下,Yi Jiang值得所有信貸在他的回答this question這裏SO。

+0

是的,我終於做了這樣的事情。 –

相關問題