2016-08-02 2 views
2

Я написал jquery, чтобы добавить читать далее/читать меньше после 250 символов. Я осуществил следующий запрос:Подробнее/Меньше использования jquery без потери html

var minimized_elements = $('.field-type-text-with-summary .field-items'); 
var minimize_character_count = 250;  
minimized_elements.each(function(){  
    var TextContent = $(this).text(); 
    var TextContentLenght = TextContent.length; 
    var t = $(this).html(); 
    if(t.length < minimize_character_count) return; 
    $(this).html(
    t.slice(0,minimize_character_count)+ 
     '<span>...</span>'+'<a href="#" class="read_more"  style="color:#FF8403;">Read more</a>'+ 
     '<span style="display:none;">'+ TextContent.slice(minimize_character_count,TextContentLenght)+'&nbsp'+'<a href="#" class="read_less" style="color:#FF8403;">Read less</a></span>' 
    ); 
    }); 
    $('a.read_more', minimized_elements).click(function(event){ 
    event.preventDefault(); 
    $(this).hide().prev().hide(); 
    $(this).next().show(); 

    }); 
    $('a.read_less', minimized_elements).click(function(event){ 
    event.preventDefault(); 
    $(this).parent().hide().prev().show().prev().show(); 

    }); 

Но моя проблема заключается в том, что этот скрипт удалить все HTML-теги, например, если текст содержит полужирный или подчеркнутый символы, показывающие, что весь текст в виде обычного текста. Я хочу читать больше/читать меньше со всем формированием. Пожалуйста, предложите. Тонны благодарности заранее.

ответ

0

Вы используете:

var TextContent = $(this).text(); 

Таким образом, вы подсчет буквы текста только при выборе вашей подстроки на основе .html(). Это будет считаться полным html, включая текст элементов.

var TextContent = $(this).html(); 

Это не простая вещь, потому что, когда вы порезали подстроку, скажем, от 0 до 250 вы можете разбить в середине элемента HTML.

Простейшим решением для хранения HTML как есть, является изменение высоты. (при чтении меньше высота элемента составляет, например, 50 пикселей, а затем на readmore это «авто» или что-то еще).

Еще одно сложное решение - это все дочерние элементы вашего основного .each(), суммируя их, и когда вы комбинируете длину .text() больше 250, вы должны поместить «readmore». (Но в зависимости от вашей структуры HTML вы должны принять во внимание, что текущая длина без детей может уже превышать 250 ...

Я рекомендую пойти с подходом высоты, если нет, вы можете сделать скрипку, и мы можем помочь вам.

+0

я изменил $ (это) .html ( t.slice (0, minimize_character_count) + ' ... '+' Read more' + « '+ t.slice (minim_character_count, TextContentLenght) +' & nbsp '+' Read less ' ); Но после этого чтение меньше не работает должным образом и начинает показывать с помощью более подробной информации. Предоставьте что-то, что не нарушит существующий скрипт. – Rajan

+0

Я редактировал свой пост. –

+0

Его немного сложно сохранить, сохраняя HTML даже для строки, которая была обрезана, и это настоящая проблема. Не могу это понять! – Rajan

0
<!doctype html> 

<html> 
<head> 
<meta charset="utf-8"> 
<title>Untitled Document</title> 
<style> 
.readLess{ display:none;} 
.conteMain{ border:1px solid #ddd; background:#f5f5f5; padding:10px; font:normal 14px Arial, Helvetica, sans-serif;} 
#conteMain p{ margin:0; padding:0;} 
.readLess,.readMore{ background:#3CF; color:#fff; padding:5px 10px; width:80px; margin:10px 0px; cursor:pointer} 
.readLess:hover,.readMore:hover{ background:#090} 
</style> 
</head> 

<body> 
<div class="conteMain"> 
<div id="conteMain"> 
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.<br> 
<br> 
<p>vived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like </p><br> 

<p>vived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like </p><br> 

<p>vived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like </p><br> 

<p>vived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like </p><br> 

<div>ved not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software l</div><br> 


It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. 
</div> 
</div> 


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
<script> 
    var conte = $("#conteMain").text().length; 
    var conte1 = $("#conteMain").text(); 
    var bx1 = conte1.slice('',200); 

    if(conte > 200){ 
     $("#conteMain").after("<span class='moreC'>"+ bx1 +"</span>"+"<div class='readMore'>Read More</div><div class='readLess'>Read Less</div>"); 
     $("#conteMain").css("display","none"); 
    }; 

    $(".readMore").click(function(){ 
     $("#conteMain").slideDown("slow"); 
     $(".moreC").css("display","none"); 
     $(".readLess").css("display","block"); 
     $(this).css("display","none"); 
    }); 

    $(".readLess").click(function(){ 
     $("#conteMain").slideUp("slow"); 
     $(".moreC").css("display","block"); 
     $(".readMore").css("display","block"); 
     $(this).css("display","none"); 
    }); 

</script> 
</body> 
</html> 
Смежные вопросы