在 <a> 标签旁边添加动态图标

Add dynamic icon beside <a> tag

我正在尝试这个 example

我正在尝试在 'Show more' 旁边添加向下箭头,在 'Show less' 旁边添加向上箭头(请参考下图)。

我尝试了以下代码示例,但仍然没有成功。

$('#nav li').each(function(i) {
$(this).append('<i class="fa' + ' ' + iconsArray[i] + '"></i>')})

如何在给定示例中添加标签旁边的图标?

您可以尝试这样的操作,并根据您的需要相应地修改代码。

Play with it here

// "READMORE" ELEMENT CONSTRUCTOR FUNCTION
const readMore = (textObj) => {
  const span = document.createElement("span")
  span.classList = "readMore"
  span.dataset.text = textObj
  const text = document.createElement("span")
  text.className = "readMoreText"
  text.innerText = "Show more"
  const icon = document.createElement("i")
  icon.classList = "icon fas fa-angle-down"
  span.append(text)
  span.append(icon)
  return span
}
const more = document.querySelectorAll(".more") //GET ALL "MORE" ELEMENTS

//ITERATE OVER ALL "MORE" ELEMENTS
more.forEach(more => {
const content = more.querySelector(".content") //GET CONTENT 
const full_text = content.innerText //GET TEXT OF CONTENT,WE NEED IT TO PASS IT TO "READMORE" FUNCTION
const short_text = full_text.substring(0, 100) + '...' //CREATE SHORT VERSION
content.innerText = short_text //SWAP CONTENT FOR SHORT VERSION
  more.appendChild(readMore(JSON.stringify({ full: full_text, short: short_text }))) //ADD "READMORE" ELEMENT TO "MORE" ELEMENT AND PASS TEXT DATA
})


//CLICK HANDLER FOR ALL 'READMORE' ELEMENTS
$(".readMore").click(function(){
const short_text = $(this).data("text").short //GET SHORT VERSION
const full_text = $(this).data("text").full //GET LONG VERSION

if ( $(this).find(".icon").hasClass("rotate") ){
  $(this).find(".icon").removeClass("rotate")
  $(this).parent().find(".content").text(short_text)
  $(this).find(".readMoreText").text("Show more")
}else{
  $(this).find(".icon").addClass("rotate")
  $(this).parent().find(".content").text(full_text)
  $(this).find(".readMoreText").text("Show less")
}

});

$(".readMore").hover(function () {
  $(this).parents(".more").css("background", "rgb(234, 234, 234)");
}, function () {
    $(this).parents(".more").css("background", "rgb(243, 243, 243)");
});
.more{
width: 500px;
background: rgb(243, 243, 243);
padding: 5px;
}

.readMore{
cursor: pointer;
user-select: none;
color: indianred;
font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
font-size: 0.9em;
}
.readMore:hover{
color: rgb(104, 104, 223);
}

.fa-angle-down{
margin-left: 0.2em;
animation: rotationBack 0.8s;
height: 13px;
}

.rotate{
transform: rotate(180deg);
animation: rotation 0.8s;
}
@keyframes rotation {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(180deg);
  }
}
@keyframes rotationBack {
  from {
    transform: rotate(180deg);
  }
  to {
    transform: rotate(0deg);
  }
}
<html>

<head>
    <title>jQuery Read More/Less Toggle Example</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css"
        integrity="sha512-Fo3rlrZj/k7ujTnHg4CGR2D7kSs0v4LLanw2qksYuRlEzO+tcaEPQogQ0KaoGN26/zrn20ImR1DfuLWnOo7aBA=="
        crossorigin="anonymous" referrerpolicy="no-referrer" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/js/all.min.js"
        integrity="sha512-fzff82+8pzHnwA1mQ0dzz9/E0B+ZRizq08yZfya66INZBz86qKTCt9MLU0NCNIgaMJCgeyhujhasnFUsYMsi0Q=="
        crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"
        integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
</head>

<body>
    <div class="more">
    <span class="content">
      Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
      tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
      veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
      commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
      velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
      cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
      est laborum.
    </span>
    </div>
    <br /><br />
    <div class="more">
    <span class="content">
        Morbi placerat imperdiet risus quis blandit. Ut lobortis elit luctus,
        feugiat erat vitae, interdum diam. Nam sit amet arcu vitae justo lacinia
        ultricies nec eget tellus. Curabitur id sapien massa. In hac
        <a href="#">habitasse</a> platea dictumst. Integer tristique leo
        consectetur libero pretium pretium. Nunc sed mauris magna. Praesent varius
        purus id turpis iaculis iaculis. Nulla <em>convallis magna nunc</em>, id
        rhoncus massa ornare in. Donec et feugiat sem, ac rhoncus mauris. Quisque
        eget tempor massa.
    </span>
    </div>
</body>

</html>

我已经设法通过对 HTML 和 JS 实施几行来解决问题。

HTML

<html>
  <head>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <title>jQuery Read More/Less Toggle Example</title>
  </head>
  <body>...
  </body>
</html>

JS

var moretext = "Show more <i class='fa fa-angle-down'></i>";
var lesstext = "Show less <i class='fa fa-angle-up'></i>";

我做了这样的事情。 (想要 post 但网站维护刚刚开始..)

<!DOCTYPE html>
<html>
  <head>
    <title>jQuery Read More/Less Toggle Example</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" integrity="sha512-Fo3rlrZj/k7ujTnHg4CGR2D7kSs0v4LLanw2qksYuRlEzO+tcaEPQogQ0KaoGN26/zrn20ImR1DfuLWnOo7aBA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <style type="text/css" media="screen">
      .morecontent span {
          display: none;
      }
      .morelink {
        display: block;
        padding: 15px;
        border: 2px solid #000;
        color: #000;
        text-decoration: none;
        max-width: 120px;
        text-align: center;
      }
      .morelink span {
        display: inline-block;
        text-decoration:underline;
      }
      .morelink i {
        display: inline-block;
      }
    </style>
  </head>
  <body>
    <span class="more">
      Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </span>
    <br><br>
    <div class="more">
      Morbi placerat imperdiet risus quis blandit. Ut lobortis elit luctus, feugiat erat vitae, interdum diam. Nam sit amet arcu vitae justo lacinia ultricies nec eget tellus. Curabitur id sapien massa. In hac <a href="#">habitasse</a> platea dictumst. Integer tristique leo consectetur libero pretium pretium. Nunc sed mauris magna. Praesent varius purus id turpis iaculis iaculis. Nulla <em>convallis magna nunc</em>, id rhoncus massa ornare in. Donec et feugiat sem, ac rhoncus mauris. Quisque eget tempor massa.
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
      $(document).ready(function() {
          // Configure/customize these variables.
          var showChar = 100;  // How many characters are shown by default
          var ellipsestext = "...";
          var moretext = "<span>Show more</span>&nbsp;&nbsp;<i class='fas fa-angle-down'></i>";
          var lesstext = "<span>Show less</span>&nbsp;&nbsp;<i class='fas fa-angle-up'></i>";
          

          $('.more').each(function() {
              var content = $(this).html();
       
              if(content.length > showChar) {
       
                  var c = content.substr(0, showChar);
                  var h = content.substr(showChar, content.length - showChar);
       
                  var html = c + '<span class="moreellipses">' + ellipsestext+ '&nbsp;</span><span class="morecontent"><span>' + h + '</span>&nbsp;&nbsp;<a href="" class="morelink">' + moretext + '</a></span>';
       
                  $(this).html(html);
              }
       
          });
       
          $(".morelink").click(function(){
              let lessMoreText = $(this).hasClass("less") ? moretext : lesstext;
              $(this).toggleClass("less").html(lessMoreText);

              $(this).parent().prev().toggle();
              $(this).prev().toggle();
              return false;
          });
      });
    </script>
  </body>
</html>