search
HomeWeb Front-endFront-end Q&AJavascript implements expansion and collapse of a piece of text

JavaScript implements the expand and collapse function of a paragraph of text

As web design pays more and more attention to user experience, more and more page designs will need to expand or collapse a paragraph of text. This Sometimes we can use JavaScript code to achieve this function. Let's take a look at how to use JavaScript to expand and collapse a piece of text.

  1. HTML code

First, we need to prepare a piece of HTML code. This code can be the text that needs to be expanded and collapsed and the rest of the page elements. The sample code is as follows:

<div class="content">
  <p>这是一段需要展开收起的文字,可以有很多很多的字,可能会占据很多的空间。因此,在默认情况下,我们只会显示部分文字,而把其余的部分折叠起来。如果需要查看全部内容,可以点击“查看更多”按钮,文字内容就会展开显示了。</p>
  <button class="btn-more">查看更多</button>
</div>

In this code, we use a <div> tag to wrap the text and button elements that need to be expanded and collapsed. In the <code><div> tag, we use a <code><p></p> tag to display the text content that needs to be expanded and collapsed. Below the text content, use a &lt ;button> tag to display the "See more" button.

  1. CSS Style

We need to use CSS to set the style of the text that needs to be expanded and collapsed in the default and expanded states.

.content p {
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  /* 设置文字溢出时显示省略号 */
}

.content p.is-expanded {
  overflow: visible;
  white-space: normal;
  /* 文字溢出时不再显示省略号 */
}

.btn-more {
  display: block;
  margin-top: 10px;
  cursor: pointer;
  /* 设置鼠标指针为手型 */
}
  1. JavaScript code

Next, we need to use JavaScript code to implement the click event of the "View More" button so that it can be expanded or collapsed when the button is clicked Text that needs to be expanded or collapsed.

First, we can create a variable to store whether it is currently in the expanded state. The initial state is false, which means it is in the collapsed state.

let isExpanded = false;

When the user clicks the "View More" button, we need to get the <p></p> element that needs to expand and collapse the text, and add or remove a # for this element. ##is-expanded's class. At the same time, change the text content of the button to display "Less" or "View More" to remind the user of the current text status.

const content = document.querySelector('.content');
const btnMore = document.querySelector('.btn-more');

btnMore.addEventListener('click', function() {
  const paragraph = content.querySelector('p');
  isExpanded = !isExpanded;
  
  if (isExpanded) {
    paragraph.classList.add('is-expanded');
    btnMore.innerText = '收起';
  } else {
    paragraph.classList.remove('is-expanded');
    btnMore.innerText = '查看更多';
  }
});

In this code, we first use the

document.querySelector() method to obtain the

elements corresponding to the text that needs to be expanded and collapsed. The

In the event listener, we will use the status of the

isExpanded variable to determine whether the current text is expanded or collapsed. If it is in the expanded state, we will add a class is-expanded to the

element and set the button's text to "Collapse". Instead, we will remove the is-expanded class and set the button's text to "See more".

So far, we have successfully implemented the expand and collapse function of a paragraph of text. When the user clicks the "View More" button, the text that needs to be expanded or collapsed can be expanded or collapsed, making the page more concise and easier to read. <p></p>

The above is the detailed content of Javascript implements expansion and collapse of a piece of text. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to Use useState() Hook in Functional React ComponentsHow to Use useState() Hook in Functional React ComponentsApr 30, 2025 am 12:25 AM

useState allows state to be added in function components because it removes obstacles between class components and function components, making the latter equally powerful. The steps to using useState include: 1) importing the useState hook, 2) initializing the state, 3) using the state and updating the function.

React's View-Focused Nature: Managing Complex Application StateReact's View-Focused Nature: Managing Complex Application StateApr 30, 2025 am 12:25 AM

React's view focus manages complex application state by introducing additional tools and patterns. 1) React itself does not handle state management, and focuses on mapping states to views. 2) Complex applications need to use Redux, MobX, or ContextAPI to decouple states, making management more structured and predictable.

Integrating React with Other Libraries and FrameworksIntegrating React with Other Libraries and FrameworksApr 30, 2025 am 12:24 AM

IntegratingReactwithotherlibrariesandframeworkscanenhanceapplicationcapabilitiesbyleveragingdifferenttools'strengths.BenefitsincludestreamlinedstatemanagementwithReduxandrobustbackendintegrationwithDjango,butchallengesinvolveincreasedcomplexity,perfo

Accessibility Considerations with React: Building Inclusive UIsAccessibility Considerations with React: Building Inclusive UIsApr 30, 2025 am 12:21 AM

TomakeReactapplicationsmoreaccessible,followthesesteps:1)UsesemanticHTMLelementsinJSXforbetternavigationandSEO.2)Implementfocusmanagementforkeyboardusers,especiallyinmodals.3)UtilizeReacthookslikeuseEffecttomanagedynamiccontentchangesandARIAliveregio

SEO Challenges with React: Addressing Client-Side Rendering IssuesSEO Challenges with React: Addressing Client-Side Rendering IssuesApr 30, 2025 am 12:19 AM

SEO for React applications can be solved by the following methods: 1. Implement server-side rendering (SSR), such as using Next.js; 2. Use dynamic rendering, such as pre-rendering pages through Prerender.io or Puppeteer; 3. Optimize application performance and use Lighthouse for performance auditing.

The Benefits of React's Strong Community and EcosystemThe Benefits of React's Strong Community and EcosystemApr 29, 2025 am 12:46 AM

React'sstrongcommunityandecosystemoffernumerousbenefits:1)ImmediateaccesstosolutionsthroughplatformslikeStackOverflowandGitHub;2)Awealthoflibrariesandtools,suchasUIcomponentlibrarieslikeChakraUI,thatenhancedevelopmentefficiency;3)Diversestatemanageme

React Native for Mobile Development: Building Cross-Platform AppsReact Native for Mobile Development: Building Cross-Platform AppsApr 29, 2025 am 12:43 AM

ReactNativeischosenformobiledevelopmentbecauseitallowsdeveloperstowritecodeonceanddeployitonmultipleplatforms,reducingdevelopmenttimeandcosts.Itoffersnear-nativeperformance,athrivingcommunity,andleveragesexistingwebdevelopmentskills.KeytomasteringRea

Updating State Correctly with useState() in ReactUpdating State Correctly with useState() in ReactApr 29, 2025 am 12:42 AM

Correct update of useState() state in React requires understanding the details of state management. 1) Use functional updates to handle asynchronous updates. 2) Create a new state object or array to avoid directly modifying the state. 3) Use a single state object to manage complex forms. 4) Use anti-shake technology to optimize performance. These methods can help developers avoid common problems and write more robust React applications.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools