【问题标题】:show more/Less text with just HTML and JavaScript仅使用 HTML 和 JavaScript 显示更多/更少的文本
【发布时间】:2021-12-03 14:36:23
【问题描述】:

我需要创建一个显示更多/更少文本的函数,但只使用 JavaScript 和 HTML。我不能使用任何额外的库,例如 jQuery,也不能使用 CSS 来完成。我添加的示例代码显示“更多”文本,而不是“更少”。

如果有人能指出我正确的方向,将不胜感激。

我一天中的大部分时间都在为此绞尽脑汁,因为这显然不是现代的做法,但是,我的 HTML 是:

<html>
<head>
<script type="text/javascript" src="moreless.js"></script>
</head>

<body>
Lorem ipsum dolor sit amet
<p>

<p id="textarea"><!-- This is where I want to additional text--></div>
</p>

<a onclick="showtext('text')" href="javascript:void(0);">See More</a>
<p>
Here is some more text 
</body>
</html>

而我的 JavaScript 是 (moreless.js):

function showtext()
{
var text="Here is some text that I want added to the HTML file";
document.getElementById("textarea").innerHTML=text;
}

【问题讨论】:

  • 为什么你需要那样做?
  • 答案会有所不同,等待您的要求的更多细节。如果您的文本将是静态的并且不会在其他地方重复。您可以切换display 就像在@akhikhl 答案中一样。这可能需要最少的代码?

标签: javascript html


【解决方案1】:

我的回答类似但不同,有几种方法可以实现切换效果。我想这取决于你的情况。这最终可能不是最适合您的方式。

您一直在寻找的缺失部分是创建一个if 语句。这允许您切换文本。

More on if statements here.

JSFiddle: http://jsfiddle.net/8u2jF/

Javascript:

var status = "less";

function toggleText()
{
    var text="Here is some text that I want added to the HTML file";

    if (status == "less") {
        document.getElementById("textArea").innerHTML=text;
        document.getElementById("toggleButton").innerText = "See Less";
        status = "more";
    } else if (status == "more") {
        document.getElementById("textArea").innerHTML = "";
        document.getElementById("toggleButton").innerText = "See More";
        status = "less"
    }
}

【讨论】:

    【解决方案2】:

    通过一些 HTML 更改,您可以完全使用 CSS 实现这一点:

    Lorem ipsum dolor sit amet
    <p id="textarea">
        <!-- This is where I want to additional text-->
        All that delicious text is in here!
    </p>
    <!-- the show/hide controls inside of the following
         list, for ease of selecting with CSS -->
    <ul class="controls">
        <li class="show"><a href="#textarea">Show</a></li>
        <li class="hide"><a href="#">Hide</a></li>
    </ul>
    
    <p>Here is some more text</p>
    

    加上CSS:

    #textarea {
        display: none; /* hidden by default */
    }
    
    #textarea:target {
        display: block; /* shown when a link targeting this id is clicked */
    }
    
    #textarea + ul.controls {
        list-style-type: none; /* aesthetics only, adjust to taste, irrelevant to demo */
    }
    
    /* hiding the hide link when the #textarea is not targeted,
       hiding the show link when it is selected: */
    #textarea + ul.controls .hide,
    #textarea:target + ul.controls .show {
        display: none;
    }
    
    /* Showing the hide link when the #textarea is targeted,
       showing the show link when it's not: */
    #textarea:target + ul.controls .hide,
    #textarea + ul.controls .show {
        display: inline-block;
    }
    

    JS Fiddle demo.

    或者,您可以使用labelinputtype="checkbox"

    Lorem ipsum dolor sit amet
    <input id="textAreaToggle" type="checkbox" />
    <p id="textarea">
        <!-- This is where I want to additional text-->
        All that delicious text is in here!
    </p>
    <label for="textAreaToggle">textarea</label>
    
    <p>Here is some more text</p>
    

    使用 CSS:

    #textarea {
        /* hide by default: */
        display: none;
    }
    
    /* when the checkbox is checked, show the neighbouring #textarea element: */
    #textAreaToggle:checked + #textarea {
        display: block;
    }
    
    /* position the checkbox off-screen: */
    input[type="checkbox"] {
        position: absolute;
        left: -1000px;
    }
    
    /* Aesthetics only, adjust to taste: */
    label {
        display: block;
    }
    
    /* when the checkbox is unchecked (its default state) show the text
       'Show ' in the label element: */
    #textAreaToggle + #textarea + label::before {
        content: 'Show ';
    }
    
    /* when the checkbox is checked 'Hide ' in the label element; the
       general-sibling combinator '~' is required for a bug in Chrome: */
    #textAreaToggle:checked ~ #textarea + label::before {
        content: 'Hide ';
    }
    

    JS Fiddle demo.

    【讨论】:

    • 这很有趣!我以前从未听说过 CSS 中的 :target。酷。
    • 很棒的纯 CSS 解决方案,除非页面上有 n 不同的 textarea 元素需要在 hideshow 之间切换,否则将无法正常工作
    【解决方案3】:

    尝试切换高度。

    function toggleTextArea()
    {
      var limitedHeight = '40px';
      var targetEle = document.getElementById("textarea");
      targetEle.style.height = (targetEle.style.height === '') ? limitedHeight : '';
    }
    

    【讨论】:

    • 这几乎对我有用。我不得不将最后一条指令更改为targetEle.style.height = (targetEle.style.height == limitedHeight) ? 'initial' : limitedHeight;
    【解决方案4】:

    这是我的纯 HTML 和 Javascript 解决方案:

    var setHeight = function (element, height) {
        if (!element) {;
            return false;
        }
        else {
            var elementHeight = parseInt(window.getComputedStyle(element, null).height, 10),
            toggleButton = document.createElement('a'),
            text = document.createTextNode('...Show more'),
            parent = element.parentNode;
    
            toggleButton.src = '#';
            toggleButton.className = 'show-more';
            toggleButton.style.float = 'right';
            toggleButton.style.paddingRight = '15px';
            toggleButton.appendChild(text);
    
            parent.insertBefore(toggleButton, element.nextSibling);
    
            element.setAttribute('data-fullheight', elementHeight);
            element.style.height = height;
            return toggleButton;
        }
    }
    
    var toggleHeight = function (element, height) {
        if (!element) {
            return false;
        }
        else {
            var full = element.getAttribute('data-fullheight'),
            currentElementHeight = parseInt(element.style.height, 10);
    
            element.style.height = full == currentElementHeight ? height : full + 'px';
        }
    }
    
    var toggleText = function (element) {
        if (!element) {
            return false;
        }
        else {
            var text = element.firstChild.nodeValue;
            element.firstChild.nodeValue = text == '...Show more' ? '...Show less' : '...Show more';
        }
    }
    
    
    var applyToggle = function(elementHeight){
        'use strict';
        return function(){
            toggleHeight(this.previousElementSibling, elementHeight);
            toggleText(this);
        }
    }
    
    
    var modifyDomElements = function(className, elementHeight){
        var elements = document.getElementsByClassName(className);
        var toggleButtonsArray = [];
    
    
        for (var index = 0, arrayLength = elements.length; index < arrayLength; index++) {
            var currentElement = elements[index];
            var toggleButton = setHeight(currentElement, elementHeight);
            toggleButtonsArray.push(toggleButton);
        }
    
        for (var index=0, arrayLength=toggleButtonsArray.length; index<arrayLength; index++){
            toggleButtonsArray[index].onclick = applyToggle(elementHeight);
        }
    }
    

    然后您可以调用 modifyDomElements 函数对所有具有短文本类名称的元素应用文本缩短。为此,您需要指定类名和希望元素缩短到的高度:

    modifyDomElements('shorten-text','50px'); 
    

    最后,在您的 html 中,只需在您希望文本缩短的元素上设置类名:

    <div class="shorten-text">Your long text goes here...</div>
    

    【讨论】:

      【解决方案5】:

      这应该可以解决您的问题:

      function toggleSeeMore() {
          if(document.getElementById("textarea").style.display == 'none') {
              document.getElementById("textarea").style.display = 'block';
              document.getElementById("seeMore").innerHTML = 'See less';
          }
          else {
              document.getElementById("textarea").style.display = 'none';
              document.getElementById("seeMore").innerHTML = 'See more';        
          }
      }
      

      完整的工作示例在这里:http://jsfiddle.net/akhikhl/zLA5K/

      【讨论】:

        【解决方案6】:

        希望您正在寻找此代码 HTML:

                    <div class="showmore">
                        <div class="shorten_txt">
                            <h4> #@item.Title</h4>
                            <p>Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text </p>
                        </div>
                    </div>
        

        脚本:

            var showChar = 100;
            var ellipsestext = "[...]";
            $('.showmore').each(function () {
                $(this).find('.shorten_txt p').addClass('more_p').hide();
                $(this).find('.shorten_txt p:first').removeClass('more_p').show();
                $(this).find('.shorten_txt ul').addClass('more_p').hide();
                //you can do this above with every other element
                var teaser = $(this).find('.shorten_txt p:first').html();
                var con_length = parseInt(teaser.length);
                var c = teaser.substr(0, showChar);
                var h = teaser.substr(showChar, con_length - showChar);
                var html = '<span class="teaser_txt">' + c + '<span class="moreelipses">' + ellipsestext +
                '</span></span><span class="morecontent_txt">' + h
                + '</span>';
                if (con_length > showChar) {
                    $(this).find(".shorten_txt p:first").html(html);
                    $(this).find(".shorten_txt p:first span.morecontent_txt").toggle();
                }
            });
            $(".showmore").click(function () {
                if ($(this).hasClass("less")) {
                    $(this).removeClass("less");
                } else {
                    $(this).addClass("less");
                }
                $(this).find('.shorten_txt p:first span.moreelipses').toggle();
                $(this).find('.shorten_txt p:first span.morecontent_txt').toggle();
                $(this).find('.shorten_txt .more_p').toggle();
                return false;
            });
        

        【讨论】:

          【解决方案7】:
           <script type="text/javascript">
               function showml(divId,inhtmText) 
               {  
                  var x = document.getElementById(divId).style.display; 
          
                  if(x=="block")
                  {
                    document.getElementById(divId).style.display = "none";
                    document.getElementById(inhtmText).innerHTML="Show More...";
                  }
                 if(x=="none")
                 {
                    document.getElementById(divId).style.display = "block";
                    document.getElementById(inhtmText).innerHTML="Show Less";
                  }
               }
          </script>
          
           <p id="show_more1" onclick="showml('content1','show_more1')" onmouseover="this.style.cursor='pointer'">Show More...</p>
          
           <div id="content1" style="display: none; padding: 16px 20px 4px; margin-bottom: 15px; background-color: rgb(239, 239, 239);">
           </div>
          

          如果更多的 div 像这样使用只更改 1 到 2

          <p id="show_more2" onclick="showml('content2','show_more2')" onmouseover="this.style.cursor='pointer'">Show More...</p>
          
           <div id="content2" style="display: none; padding: 16px 20px 4px; margin-bottom: 15px; background-color: rgb(239, 239, 239);">
           </div>
          

          演示 jsfiddle

          【讨论】:

            【解决方案8】:

            我不是专家,但我做了很多尝试来为自己实现这一点。我发现了一些不同的东西,但对其进行了修改以实现这一点。其实很简单:

            该函数有两个参数,一个只包含“显示更多”[或其他]的 div 和一个包含最初隐藏的文本和“显示更少”的 div。该函数显示一个div并隐藏另一个。

            注意:如果页面上有多个显示/隐藏,请为 div 分配不同的 id 颜色可以改变

            <p>Here is text that is originally displayed</p>
            
            <div id="div1">
            <p style="color:red;" onclick="showFunction('div2','div1')">show more</p></div>
            <div id="div2" style="display:none">
            
            <p>Put expanded text here</p>
            
            <p style="color:red;" onclick="showFunction('div1','div2')">show less</p></div>
            
            <p>more text</p>
            

            这是脚本:

            <script>
            function showFunction(diva, divb) {
                var x = document.getElementById(diva);
                var y = document.getElementById(divb);
                      x.style.display = 'block';
                      y.style.display = 'none';
            }
            </script>
            

            【讨论】:

              【解决方案9】:

              你也可以使用details HTML 标签来为你工作。

              <details>
                <summary>Epcot Center</summary>
                <p>Epcot is a theme park at Walt Disney World Resort featuring exciting attractions, international pavilions, award-winning fireworks and seasonal special events.</p>
              </details>
              

              来源W3CSchool

              【讨论】:

                【解决方案10】:

                我希望这对你有帮助。这是功能:

                • text字符小于等于 12。然后显示整个text,并且不显示更多/更少按钮
                • 文本字符超过12个时。仅显示 12 个字符文本 以及一个 More 按钮,当按下该按钮时,将显示 整个文本.
                • 更多按钮被按下时,按钮变为更少

                阅读 w3schools 中的更多字符串操作:String Manipulation 或 莫兹拉:String Manipulation

                var startStatus = "less";
                
                function toggleText() {
                  var text = "Here is the text that I want to play around with";
                
                  if (text.length > 12) {
                    if (startStatus == "less") {
                      document.getElementById("textArea").innerHTML = `${text.substring(0, 12)}...`;
                      document.getElementById("more|less").innerText = "More";
                      startStatus = "more";
                    } else if (startStatus == "more") {
                      document.getElementById("textArea").innerHTML = text;
                      document.getElementById("more|less").innerText = "Less";
                      startStatus = "less";
                    }
                  } else {
                    document.getElementById("textArea").innerHTML = text;
                  }
                }
                
                toggleText();
                <!DOCTYPE html>
                <html lang="en">
                
                <head>
                  <meta charset="UTF-8" />
                  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
                  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
                  <title>Document</title>
                </head>
                
                <body>
                  <div>
                    <p id="textArea">
                      <!-- This is where i want text displayed-->
                    </p>
                    <span><a
                          id="more|less"
                          onclick="toggleText();"
                          href="javascript:void(0);"
                        ></a
                      ></span>
                  </div>
                </body>
                
                </html>

                【讨论】:

                  猜你喜欢
                  • 2020-06-18
                  • 1970-01-01
                  • 2021-12-20
                  • 1970-01-01
                  • 2018-07-27
                  • 2019-09-12
                  • 1970-01-01
                  • 2020-04-20
                  • 1970-01-01
                  相关资源
                  最近更新 更多