2014-05-13 23 views
1

我想製作一個Jquery腳本,如果它溢出#box div之外,將在文本週圍放置標籤標籤。文本顯然比30px寬,而div確實隱藏了大部分文本。我的問題是沒有出現選取框效果。這裏是我的完整代碼:當文本溢出時製作JQuery字幕

<!doctype html> 
<html> 
<head> 
<meta charset="utf-8"> 
<title>Untitled Document</title> 
<style> 
#box { 
    width:30px; 
    overflow:hidden; 
} 
</style> 
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
</head> 

<body> 

<div id="box"> 
Overflooooooooooow 
</div> 

<script> 

$(function(){ 
    $box = $('#box'); 
    $box.children().each(function(){ 
    if ($box.width() < $(this).width()) { 
     $(this).wrap('<marquee>'); 
    } 
    }); 
}); 
</script> 
</body> 
</html> 

謝謝你的幫助。所有的幫助表示讚賞。

+3

_「另請注意,最喜歡的jQuery方法,。孩子()不返回文本節點,讓所有的孩子,包括文字和註釋節點,用.contents()」 _ – j08691

回答

3

div內的文本只是一個文本節點,而不是可以獲得寬度的元素。只需添加一個內部塊元素:

<div id="box"> 
    <div>Overflooooooooooow</div> 
</div> 

編輯:

對不起,不會與內部DIV工作,因爲它繼承了父母的默認寬度。使用範圍:

<div id="box"> 
    <span>Overflooooooooooow</span> 
</div> 
+0

這即使在實施後仍然不起作用。 – Kelsey

+2

是的......我幾乎發佈了一個答案,但後來你糾正了它。該div不工作,因爲它的'display:block'。跨度,默認爲'display:inline'。如果你將inner div設置爲'display:inline',它也可以工作。 – LcSalazar

+0

它現在有效,謝謝你們兩位。 – Kelsey