请您能帮我解决如何撤消子字符串的问题,因为当我单击一个按钮(跨度)时,我想使文本恢复其正常长度,并且还希望使按钮在使用javascript单击后消失。我尝试使用的代码

的HTML

<p class="bio">
   Lorem ipsum dolor sit amet, hello how consectetur
   adipisicing elit. Sint consectetur provident magni
   yohoho consequuntur, voluptatibus ghdfff exercitationem
   at quis similique. Optio, amet!
</p>


Javacript

let bio = document.querySelector('.bio');
const bioMore = document.querySelector('#see-more-bio');
const bioLength = bio.innerText.length;

function bioText() {
   bio.innerText = bio.innerText.substring(0, 100) + "...";
   bio.innerHTML += `<span onclick='addLength()' id='see-more-bio'>See More</span>`;
}
console.log(bioLength)

bioText();

function addLength() {
   bio.innerText = bio.innerText.substring(0, bioLength);
   bioMore.style.display = "none";
}

最佳答案

您可以做的另一种选择是将零件分开并将其放在可以有条件地显示需要显示的内容的跨度中。然后,在单击选项时翻转可见性。



[...document.querySelectorAll('.bio')].forEach(bio => {
  if (bio.innerText.length <= 100) return;

  const more = `
    <span class="ellipsis">...</span>
    <span class="more">${bio.innerText.slice(100)}</span>
    <a href="#" class="show-more">Show More</a>
  `;

  bio.innerHTML = bio.innerText.slice(0, 100) + more;

  bio.querySelector('.show-more').addEventListener('click', e => {
    e.target.parentNode.classList.add('show-more');
  });
});

.bio:not(.show-more) .more { display: none; }
.bio.show-more .ellipsis, .bio.show-more .show-more { display: none; }

<p class="bio">
   Lorem ipsum dolor sit amet, hello how consectetur
   adipisicing elit. Sint consectetur provident magni
   yohoho consequuntur, voluptatibus ghdfff exercitationem
   at quis similique. Optio, amet!
</p>

<p class="bio">
   Lorem ipsum dolor sit amet, hello how consectetur
   adipisicing elit. Sint consectetur provident magni
   yohoho consequuntur, voluptatibus ghdfff exercitationem
   at quis similique. Optio, amet!
</p>

09-27 01:30