使用 JS 单击更改图标

Change Icon on click with JS

我有以下 html 个标签:

<p class=font-ms>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, 
  nulla et dictum interdum, nisi lorem egestas vitae scel
  <span id="dots">...</span>
  <span id="more">
    erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue 
    eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc 
    sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed 
    nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus 
    gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus 
    pulvinar nibh tempor porta.
  </span>
</p>
<a class="purple-head hover-black" onclick="changeIcon()" id="myBtn">
  <i id="faPlus" class="fa fa-plus font-xs"></i>
  Read more
</a>

现在我只想让页面显示更多跨度并将图标从加号切换到图标减号并将阅读更多内容切换为更少阅读内容?

因此 select 元素并切换 class 以更改图标。检查状态并设置文本。

function changeIcon(anchor) {
  var icon = anchor.querySelector("i");
  icon.classList.toggle('fa-plus');
  icon.classList.toggle('fa-minus');

   anchor.querySelector("span").textContent = icon.classList.contains('fa-plus') ? "Read more" : "Read less";
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet" />
<a class="purple-head hover-black" onclick="changeIcon(this)" id="myBtn">
  <i id="faPlus" class="fa fa-plus font-xs"></i>
  <span>Read more</span>
</a>

其他选项只是向包装器添加 class 并更改显示的元素。

function changeIcon(anchor) {
  anchor.closest('.wrapper').classList.toggle('active');
}
.wrapper p {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.wrapper.active p {
  white-space: normal;
  overflow: visible;
}


.wrapper .less {
  display: none;
}

.wrapper.active .less {
  display: inline;
}

.wrapper.active .more {
  display: none;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet" />
<div class="wrapper">
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut tincidunt quis nunc euismod cursus. In non metus pharetra, vehicula sem eget, venenatis eros. Maecenas congue quam mauris, eget pretium sem mollis non. Vivamus varius neque sit amet orci sodales, non varius dui ullamcorper. Maecenas rutrum dapibus porta. Sed augue tellus, maximus id commodo nec, fringilla sed velit. Duis diam nisi, porttitor sit amet fringilla quis, tempor quis purus. Aenean elit dui, egestas ac mauris eu, finibus suscipit turpis. Aenean non sapien id ex euismod euismod. Nunc commodo vestibulum libero, at bibendum risus. Nam sagittis nec quam id egestas. Maecenas egestas egestas feugiat.</p>
  <a class="purple-head hover-black" onclick="changeIcon(this)" id="myBtn">
    <i class="more fa fa-plus font-xs"></i>
    <span class="more">Read more</span>
    <i class="less fa fa-minus font-xs"></i>
    <span class="less">Read less</span>
  </a>
</div>