How to change color of letter on mouse hover in JavaScript

后端 未结 3 452
长发绾君心
长发绾君心 2020-12-31 15:54

This is my code:



        
相关标签:
3条回答
  • 2020-12-31 16:04

    You can first create a new HTML content using <span class='x'> for each character in <p> and then replace the HTML of <p> with that HTML. Now, when you hover over each character then the color of that character changes to orange

    $(document).ready(function(){
      var letters = $('p').text();
      var nHTML = '';
      for(var letter of letters) {
        nHTML+="<span class='x'>"+letter+"</span>";
      }
      $('p').html(nHTML);
    })
    .x:hover {
      color: orange;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <p>Hello World!</p>

    0 讨论(0)
  • 2020-12-31 16:07

    You can definitely solve this problem using CSS. Create a div and inside write a text command with an id. Use the id to reference it in CSS.

    .id:hover{
        color: blue;
    }
    
    0 讨论(0)
  • 2020-12-31 16:10

    You can wrap every letter with a span with class x for example.

    Example:

    $("#x").html(
      $("#x").text().split("").map(a => `<span class="x">${a}</span>`)
    )
    .x:hover {
      color: red;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <p id="x">Hello World!</p>

    0 讨论(0)
提交回复
热议问题