You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery实现不同屏幕尺寸文本截断失效,请求代码写法排查

Hi there! Let's walk through the issues in your code and fix them step by step to get your desired text truncation behavior working correctly.

Key Issues in Your Current Code

  • Only runs once on page load: Your script checks the window width a single time when the page finishes loading, but doesn't re-execute if the user resizes their screen. This means the truncation won't update if the viewport changes size.
  • Counts HTML tags as characters: Using $(this).html().length includes any HTML markup in your character count, which gives inaccurate results (e.g., hidden tags or formatting will add to the length even though they aren't visible text).
  • CSS media query hides buttons incorrectly: Your @media(max-width:768px) rule hides the .info-more button entirely, which contradicts your requirement to show it when text exceeds 100 characters on small screens.
  • Overwrites original content: When you replace the HTML of .info_content, you lose the full original text—so you can't revert back or recalculate truncation later if needed.

Fixed Code Implementation

HTML (No Changes Needed)

We'll keep your existing structure, and our JavaScript will add a data attribute to store the original full text:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="info_content">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Accusamus quaerat quidem beatae, sit nesciunt facilis odio reiciendis esse maxime. Eos dolorum nesciunt odit officiis possimus quis quia officia commodi ipsa repudiandae doloribus velit sint itaque, atque veritatis eveniet? Iste minima odio earum soluta accusamus consectetur esse blanditiis enim voluptates animi obcaecati eius corporis explicabo consequuntur magni reprehenderit veritatis nemo sed perspiciatis numquam, laborum nihil excepturi a. Commodi pariatur molestiae excepturi praesentium vitae voluptate, doloribus ad consequatur esse voluptatibus placeat, nam quas officiis libero qui obcaecati. Quia ipsum molestias quis iure quasi nobis odit vero, dolorem voluptatem error corporis vitae neque!</p>

CSS

We'll remove the broken media query and style the button to blend with text:

.info_content{
  width: 500px;
  border:1px solid #222;
}
.info-more{
  background: none;
  border: none;
  font-weight: 500;
  color: blue;
  cursor: pointer;
  padding: 0;
  margin-left: 4px;
}
.info-more:hover{
  text-decoration: underline;
}

JavaScript

This version fixes all the issues and adds a toggle for expanding/collapsing text:

$(function(){
  // Save the original full text for each content block
  $('.info_content').each(function(){
    $(this).data('originalText', $(this).text());
  });

  // Core function to handle text truncation based on screen size
  function truncateText() {
    const charLimit = $(window).width() <= 768 ? 100 : 50;

    $('.info_content').each(function(){
      const $content = $(this);
      const originalText = $content.data('originalText');

      if (originalText.length > charLimit) {
        // Truncate text and add showmore button
        const truncated = originalText.substring(0, charLimit) + "...";
        $content.html(`${truncated}<button class='info-more'>showmore</button>`);
        $content.removeClass('expanded');
      } else {
        // Restore full text if it's shorter than the limit
        $content.text(originalText);
      }
    });
  }

  // Run truncation on page load
  truncateText();

  // Re-run truncation when window is resized (with a delay to avoid excessive calls)
  let resizeTimer;
  $(window).on('resize', function(){
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(truncateText, 250);
  });

  // Handle showmore/showless button clicks
  $(document).on('click', '.info-more', function(){
    const $content = $(this).closest('.info_content');
    const originalText = $content.data('originalText');

    if ($content.hasClass('expanded')) {
      // Collapse back to truncated text
      truncateText();
    } else {
      // Show full text and switch to showless button
      $content.text(originalText).append("<button class='info-more'>showless</button>");
      $content.addClass('expanded');
    }
  });
});

Key Improvements Explained

  • Preserved original text: Using data('originalText') stores the full content so we can toggle between truncated and full versions without losing data.
  • Accurate character count: $(this).text() counts only visible text, ignoring any HTML markup.
  • Responsive to window resizing: The resize listener with a timeout ensures truncation updates when the screen size changes, without running too frequently.
  • Toggle functionality: Users can now expand to see full text and collapse back to truncated text with a single button.
  • Fixed button styling: The button now looks like inline text, making the UI feel more natural.

内容的提问来源于stack exchange,提问作者WEI A

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 17:32:41