首页 > 解决方案 > Read More / Read Less 按钮 - 当点击 Read Less 时,它会失去它的位置,而不是回到原来的位置

问题描述

我的网站上有一个阅读更多/阅读更少按钮来隐藏长文本。我的网站位于以下链接:( http://raywebsolution.com/mcmillan ) 我的问题是,当我单击“阅读少”按钮关闭扩展区域时,它不会回到我在网站上的位置. 它完全失去了它的位置。我正在添加一个我使用过的代码示例。

function readMoreRome() { //finds function
    var dots = document.getElementById("dots"); //returns element that has the ID attribute with value, searches for dots
    var moreText = document.getElementById("more"); // '' '' searches for more
    var btnText = document.getElementById("myBtn"); // '' '' searches for myBtn

    if (dots.style.display === "none") {
        dots.style.display = "inline";
        btnText.innerHTML = "Read more"; //button says read more to show more text
        moreText.style.display = "none";
    } else {
        dots.style.display = "none";
        btnText.innerHTML = "Read less"; //button says read less to show less text
        moreText.style.display = "inline";
    }
}

function readMoreBuda() { //finds function
    var dots = document.getElementById("dots2"); //returns element that has the ID attribute with value
    var moreText = document.getElementById("more2"); // '' '' searches for more2
    var btnText = document.getElementById("myBtn2"); // '' '' searches for myBtn2

    if (dots.style.display === "none") {
        dots.style.display = "inline";
        btnText.innerHTML = "Read more"; //button says read more to show more text
        moreText.style.display = "none";
    } else {
        dots.style.display = "none";
        btnText.innerHTML = "Read less"; //button says read less to show less text
        moreText.style.display = "inline";
    }
}
<div class="card">
    <h2>Visit Budapest</h2>
    <div class="info"> <span class="date"><i class="far fa-calendar"></i> November 12, 2019</span> <span class="comment"><i class="far fa-comment-alt"></i> 2 comments</span> </div>
    <div class="img"><img src="img/szechenyi.jpg" style="height:200px;"> </div>
    <p><i>Széchenyi Thermal Baths </i></p>
    <p>
        Budapest is the capital city of Hungary. It is best known for its arts and culture. It is a relatively small city, however there are much to see and do.
        <span id="dots2">...</span>
        <span id="more2">Situated on thermal springs, there are many naturally heated baths to relax in, the Széchenyi baths are the largest with 15 indoor baths and 3 outdoor. There are many spectacular viewpoints in Budapest, great for capturing the views of the city. From 360 panoramic views up at St Stephens Basilica to a wide view of the parliament and the River at Fisherman’s Bastion. Visit the Museum of Fine Arts and enjoy a day amongst famous European art. Classical music lovers will appreciate a performance at the Academy of Music.</span>
    </p>
    <button onclick="readMoreBuda()" id="myBtn2">Read more</button>
</div>
<br>
<div class="card">
    <h2>Visit Barcelona</h2>
    <div class="info"> <span class="date"><i class="far fa-calendar"></i> December 06, 2019</span> <span class="comment"><i class="far fa-comment-alt"></i> 5 comments</span> </div>
    <div class="img"><img src="img/guell-park.jpg" style="height:200px;"></div>
    <p><i>Park Güell </i></p>
    <p>
        Barcelona, framed for its individuality, cultural interest, and physical beauty, home to art and architecture. Facing the Mediterranean to the southeast,
        <span id="dots3">...</span>
        <span id="more3"> the city is one of a kind. Upon visiting make sure you visit the spectacular and unique Park Güell which was firstly designed for a town up in the mountains by artist Antoni Gaudí. Gaudí's work is admired by architects around the World as being one of the most unique and distinctive styles in modern architecture. Other places worth visiting is the La Sagrada Família, is a giant basilica. With beaches on your doorstop, and art and city culture, this diverse city has everything to offer.</span>
    </p>
    <button onclick="readMoreBarca()" id="myBtn3">Read more</button>
</div>

标签: javascripthtmlcss

解决方案


您应该保持代码DRY,让机器为您完成工作,而不是为每张卡片编写处理函数。当您根本不需要更新 JS 部分,添加或删除或重新排列卡片时,更新页面也会更方便。为此,我们使用id较少的标记,如下所示:

const allCards = document.querySelectorAll('.all-cards');

function toggleText (e) {
    if (e.target.tagName !== 'BUTTON') {return;} // Quit, not clicked on a button
    const button = e.target,
    card = e.target.parentElement,
    hide = card.querySelector('.three-dots'),
    show = card.querySelector('.expanded-text'),
    state = !+button.getAttribute('data-state'),
    pos = +button.getAttribute('data-pos');

  // Make the changes to the page
  hide.classList.toggle('hidden');
  show.classList.toggle('hidden');
  button.setAttribute('data-state', +state);
  button.textContent = (state) ? 'Read less' : 'Read more';
  
  // Save/adjust scroll position
  // posDelta depends on the space to scroll after the last card.
  // If there is space, toggle the comment on the const lines below
  const posDelta = (button.parentElement === allCards.lastElementChild) ? 0 : -show.offsetHeight;
  // const posDelta = -show.offsetHeight;  
  if (state) {
    e.target.setAttribute('data-pos', posDelta);
  } else {
    window.scrollBy(0, pos);
  }

  return;
}

// Attach an event listener for each `.all-cards` element on the page
allCards.forEach(card => card.addEventListener('click', toggleText));
.hidden {
  display: none;
}
.card img {
  height: 200px;
}
<div class="all-cards">
  <div class="card">
      <h2>Visit Budapest</h2>
      <div class="info"> <span class="date"><i class="far fa-calendar"></i> November 12, 2019</span> <span class="comment"><i class="far fa-comment-alt"></i> 2 comments</span> </div>
      <div class="img"><img src="img/szechenyi.jpg"> </div>
      <p><i>Széchenyi Thermal Baths </i></p>
      <p>
          Budapest is the capital city of Hungary. It is best known for its arts and culture. It is a relatively small city, however there are much to see and do.
          <span class="three-dots">...</span>
          <span class="expanded-text hidden">Situated on thermal springs, there are many naturally heated baths to relax in, the Széchenyi baths are the largest with 15 indoor baths and 3 outdoor. There are many spectacular viewpoints in Budapest, great for capturing the views of the city. From 360 panoramic views up at St Stephens Basilica to a wide view of the parliament and the River at Fisherman’s Bastion. Visit the Museum of Fine Arts and enjoy a day amongst famous European art. Classical music lovers will appreciate a performance at the Academy of Music.</span>
      </p>
      <button data-state="0">Read more</button>
  </div>
  <br>
  <div class="card">
      <h2>Visit Barcelona</h2>
      <div class="info"> <span class="date"><i class="far fa-calendar"></i> December 06, 2019</span> <span class="comment"><i class="far fa-comment-alt"></i> 5 comments</span> </div>
      <div class="img"><img src="img/guell-park.jpg"></div>
      <p><i>Park Güell </i></p>
      <p>
          Barcelona, framed for its individuality, cultural interest, and physical beauty, home to art and architecture. Facing the Mediterranean to the southeast,
          <span class="three-dots">...</span>
          <span class="expanded-text hidden"> the city is one of a kind. Upon visiting make sure you visit the spectacular and unique Park Güell which was firstly designed for a town up in the mountains by artist Antoni Gaudí. Gaudí's work is admired by architects around the World as being one of the most unique and distinctive styles in modern architecture. Other places worth visiting is the La Sagrada Família, is a giant basilica. With beaches on your doorstop, and art and city culture, this diverse city has everything to offer.</span>
      </p>
      <button data-state="0">Read more</button>
  </div>
</div>

注意,所有的ids 和 inline 事件都被删除了,并且类hidden被添加到 span 中以在页面加载时隐藏。我们使用JS中的addEventListener将单击事件委托给所有卡片的包装元素,而不是内联事件。在处理函数中,我们可以从事件的事件对象中找到被点击的按钮,该对象被浏览器自动传递给事件处理函数(e代码中的参数)。内联样式也被简单的类名更改所取代,这减少了代码并使一切变得更加简单。

目标元素在 HTML (three-dotsexpand-text) 中标有类属性。该代码将展开文本的高度存储到data-pos按钮的属性中,并在单击“少读”按钮时恢复原始位置。data-state属性存储用于更改页面视图的信息。按钮必须是卡片 div 的直接子元素,标记结构的其他部分可以更改,只要保留三点跨度的类和展开元素的文本即可。

如果您总是在卡片之后的页面上有更多内容,或者页面有一个公平的下边距,那么您可以删除较长的版本posDelta,而只使用较短的版本。


推荐阅读