<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> <script type="text/javascript"> (function( $ ){ $.fn.correctLines = function( maxLine, moreText ) { var self = this[ 0 ], temp, classes, i, lineHeight; maxLine = ( temp = /^(?:.*\s)?fixline_([\d]+)(?:\s.*)?$/.exec( self.className ) ) && temp[1] || maxLine || 3; moreText = moreText || '...<br />'; var clone = $( self ).clone( true ). css( {"height": "auto", "width": self.offsetWidth + "px"} ).html("W"); clone.appendTo( document.body ); lineHeight = this.css('line-height'); if ( lineHeight == "normal" ) { lineHeight = clone[0].clientHeight; } else if ( ( lineHeight + '' ).indexOf("px") > 0 ) { lineHeight = parseInt( lineHeight ); } else { lineHeight = parseInt( this.css('font-size') ) * parseFloat( lineHeight ); } var height = lineHeight, width = self.offsetWidth, lines = 0, lastHeight = 0, startWord = 0, endWord = -1, txt = self.innerHTML.split(" "), part = []; clone.empty(); for( i = 0; i < txt.length; i++ ) { clone[0].innerHTML += txt[ i ] + ' '; if ( clone[0].offsetHeight > lastHeight ) { if ( lastHeight == 0 ) { height = clone[0].offsetHeight; } startWord = endWord + 1; endWord = i - 1; lastHeight = clone[0].offsetHeight; if ( ++lines > maxLine ) { break; } } } if ( lines > maxLine ) { this.css({height: ( lineHeight * maxLine ) + "px", overflowY: 'hidden'}); part = txt.slice( startWord, endWord + 1 ); for( i = part.length - 1; i >= 0; i-- ) { clone.html( part.join(' ') + moreText ); if ( clone[0].offsetHeight > height ) { part.splice( i, 1 ); endWord--; } else { break; } } txt[ endWord ] += moreText; self.innerHTML = txt.join(" "); } else { this.css({height: "auto"}); } clone.remove(); } })( jQuery ); </script> <style>.fvem{width:20%;font-size:14px;border:1px solid #000000;}</style> <div class="fvem"> <div class="correct_comment">Loremipsudolorsitmet, consecteturadipiscingelit. Nulla tincidunt nunc commodo magna posuere sollicitudin. Quisque ultrices sodales nisi eu sagittis.</div> </div> <script type="text/javascript"> jQuery(".correct_comment").correctLines( 3, '<span onclick="jQuery(this).parent().css(\'height\', \'auto\').end().hide();">... <span style="color: #f00; text-decoration: underline; cursor: pointer;">more</span></span>' ); </script> |
Gozar,
ща подумаю над этим, где-то что-то я упустил |
devote,
Некоторые вещи лучше не делать чем делать. Идея забавна, но по мне так маложизнеспособна. |
Это был не самый распространенный вариант, а теперь сюрприз, самый распространенный:
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> <script type="text/javascript"> (function( $ ){ $.fn.correctLines = function( maxLine, moreText ) { var self = this[ 0 ], temp, classes, i, lineHeight; maxLine = ( temp = /^(?:.*\s)?fixline_([\d]+)(?:\s.*)?$/.exec( self.className ) ) && temp[1] || maxLine || 3; moreText = moreText || '...<br />'; var clone = $( self ).clone( true ). css( {"height": "auto", "width": self.offsetWidth + "px"} ).html("W"); clone.appendTo( document.body ); lineHeight = this.css('line-height'); if ( lineHeight == "normal" ) { lineHeight = clone[0].clientHeight; } else if ( ( lineHeight + '' ).indexOf("px") > 0 ) { lineHeight = parseInt( lineHeight ); } else { lineHeight = parseInt( this.css('font-size') ) * parseFloat( lineHeight ); } var height = lineHeight, width = self.offsetWidth, lines = 0, lastHeight = 0, startWord = 0, endWord = -1, txt = self.innerHTML.split(" "), part = []; clone.empty(); for( i = 0; i < txt.length; i++ ) { clone[0].innerHTML += txt[ i ] + ' '; if ( clone[0].offsetHeight > lastHeight ) { if ( lastHeight == 0 ) { height = clone[0].offsetHeight; } startWord = endWord + 1; endWord = i - 1; lastHeight = clone[0].offsetHeight; if ( ++lines > maxLine ) { break; } } } if ( lines > maxLine ) { this.css({height: ( lineHeight * maxLine ) + "px", overflowY: 'hidden'}); part = txt.slice( startWord, endWord + 1 ); for( i = part.length - 1; i >= 0; i-- ) { clone.html( part.join(' ') + moreText ); if ( clone[0].offsetHeight > height ) { part.splice( i, 1 ); endWord--; } else { break; } } txt[ endWord ] += moreText; self.innerHTML = txt.join(" "); } else { this.css({height: "auto"}); } clone.remove(); } })( jQuery ); </script> <style>.fvem{width:200px;font-size:14px;border:1px solid #000000;}</style> <div class="fvem"> <div class="correct_comment">Loremipsud <div style="font-size:45px">olorsitmet</div>, consecteturad ipiscingelit. Nulla tincidunt nunc commodo magna posuere sollicitudin. Quisque ultrices sodales nisi eu sagittis.</div> </div> <script type="text/javascript"> jQuery(".correct_comment").correctLines( 3, '<span onclick="jQuery(this).parent().css(\'height\', \'auto\').end().hide();">... <span style="color: #f00; text-decoration: underline; cursor: pointer;">more</span></span>' ); </script> |
Gozar,
Все поправил, можешь наслаждаться =) |
devote,
Как же я могу наслаждаться если второй блок имеет прокрутку и текст не читается? Гибкость настройки такого плагина сравнима с кирпичом. В то же самое время любой веб мастер порежет текст до помещающихся в, заранее известного размера, блок символов текста, обрезая их по последнему пробелу и это все уместиться в 1-2 строки. |
Все сделал, куча всего даже снес =) Но вообще не рекомендуется пихать в текст теги с какими либо атрибутами... Но хотя щас я это учел...
Наслаждайтесь! ))) |
Цитата:
|
devote,
Не пользователи для программистов, а программисты для пользователей. Вот три причины по которым лично я не буду использовать этот плагин никогда: 1. Слишком большой скрипт, для решения задач вёрстки. Если можно решить проблему вёрсткой - css+html, то я буду решать задачу вёрсткой. 2. Пользователи пихают в текст всё подряд и придется резать теги скриптом, а значит нужен в 4 раза короче скрипт, который будет резать теги и заодно обрезать по символу. 3. На сайте может и чаще всего бывает и так много скриптов и нужна очень веская причина подключить ещё один. |
Цитата:
Цитата:
Цитата:
|
Часовой пояс GMT +3, время: 10:58. |