仅使用HTML和JavaScript显示更多/更少的文本

时间:2013-12-23 00:58:34

标签: javascript html

我需要创建一个显示更多/更少文本功能,但只使用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;
}

8 个答案:

答案 0 :(得分:11)

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

您一直在寻找的缺失部分是创建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"
    }
}

答案 1 :(得分:5)

通过一些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

或者,您可以使用labelinput type="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

答案 2 :(得分:1)

这是我纯粹的HTML&amp; 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>

答案 3 :(得分:0)

尝试切换身高。

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

答案 4 :(得分:0)

这可以解决您的问题:

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/

答案 5 :(得分:0)

希望您正在寻找此代码 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>

SCRIPT:

    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;
    });

答案 6 :(得分:0)

 <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

答案 7 :(得分:0)

我不是专家,但我做了很多寻求为自己实现这一点。我找到了不同的东西,但修改它来实现这一目标。这真的很简单:

该函数有两个参数,一个只包含单词“show more”[或者其他]的div和一个包含原始隐藏文本和单词“show less”的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>