使用javascript使用“Read More”链接动态缩短文本

时间:2014-01-27 15:43:49

标签: javascript

我正在使用下面的代码使用java脚本创建“Read More”的功能,但无法提供适当的功能。我的限制是我不能在代码中使用jQuery。

HTML代码: -

<div id="GBPLandingRgtBtmCntt" >
  <%out.flush();%>
    <c:import url="${jspStoreDir}/Snippets/Marketing/Content/ContentSpotDisplay.jsp">
      <c:param name="spotName" value="GiveBackPrgm_Landing_right_bottom_Content_spot" />
      <c:param name="catalogId" value="${WCParam.catalogId}" />
      <c:param name="storeId" value="${WCParam.storeId}" />
    </c:import>
  <%out.flush();%>
</div>

JavaScript代码: -

<script>
  window.onload = dynamicExpandShortenedText();

  function dynamicExpandShortenedText() {

    var showChar = 1500;
    var ellipsisText = "...";
    var moreText = "Read More";
    var lessText = "Read Less";
    var rgtBtmCnttElement = document.getElementById("GBPLandingRgtBtmCntt");
    var rgtBtmCnttHtml = rgtBtmCnttElement.innerHTML;
    alert(rgtBtmCnttHtml.length);
    alert(showChar);
    if(rgtBtmCnttHtml.length > showChar) {

      var c = rgtBtmCnttHtml.substr(0, showChar);
      var h = rgtBtmCnttHtml.substr(showChar-1, rgtBtmCnttHtml.length - showChar);
      var html = c + '<span>' + ellipsisText + '&nbsp;</span>'
      + '<span>' + h + '</span>'
      + '&nbsp;&nbsp;<a id="dynamicMoreLessAnchorId" href="#" onclick="javascript:switchMoreLessLink();return false;">' + moreText + '</a>';

      rgtBtmCnttElement.innerHTML = html;
    }
  }

  function switchMoreLessLink() {
    var moreText = "Read More";
    var lessText = "Read Less";
    var dynamicMoreLessAnchorIdElement = document.getElementById("dynamicMoreLessAnchorId");
    if(dynamicMoreLessAnchorIdElement.className == 'less'){
      dynamicMoreLessAnchorIdElement.classList.remove('less');
      dynamicMoreLessAnchorIdElement.innerHTML = moreText;
    } else {
      dynamicMoreLessAnchorIdElement.classList.add('less');
      dynamicMoreLessAnchorIdElement.innerHTML = lessText;
    }
    dynamicMoreLessAnchorIdElement.getParent().prev().toggle();
    dynamicMoreLessAnchorIdElement.prev().toggle();
    return false;

  }

</script>

请说明我错了。

1 个答案:

答案 0 :(得分:0)

我为滑块信息框创建了这样一个功能。它按字面切割文本长度。对于很长的文本,存在优化潜力

<强> Demo

ShortenText = function (elements) {
    $(elements).each(function () {
        while (!checkIfTextFits(this) && $(this).text().length > 0) {
            shortenText(this);
        }
    });

    function checkIfTextFits(elem) {
        if ($(elem).parent().parent().innerHeight() < $(elem).parent().parent()[0].scrollHeight) {
            return false;
        }
        return true;
    }

    function shortenText(elem) {
        $(elem).text($(elem).text().substr(0, $(elem).text().lastIndexOf(' ')));
    }
};