Change character color on hover over javascript

I am trying to highlight (change the background color) a character that is hovering over a mouse.

how can i do this using javascript?

he should create code similar to this

<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr,
sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat,
sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.
Stet clita kasd gubergren, no sea takimata sanctus <span id='highlight'>e</span> Lorem     ipsum dolor sit amet.</p>
+3
source share
3 answers

You can divide your paragraph into characters. Then map each character to the range containing the character, then add these elements to the empty paragraph. Give each step a CSS block :hover:

JQuery

$cont = $('p');
parts = $.map($cont.text().split(''), function(v){
    return $('<span />', {text:v});
});
$cont.empty().append(parts);

CSS

p span:hover{background:#F00}

Jsfiddle


If you want to leave a space, use the if statement to check the length of the value after triming:

$cont = $('p');
parts = $.map($('p').text().split(''), function(v){
    return $.trim(v).length ? $('<span />', {text:v}) : ' ';
});
$cont.empty().append(parts);

Jsfiddle

+3
source

EDIT: OP Javascript jQuery. , , . , jQuery .


, , <span>, .

HTML :

<p id="source">This is an example text.</p>

JS :

var i, tx, html, node;

node = document.getElementById("source");
tx = node.innerHTML;

html = "";
for (i = 0; i < tx.length; i++)
{
  html += "<span>" + tx.charAt(i) + "</span>";
}

node.innerHTML = html;

CSS:

p#source span:hover
{
  background-color: red;
}

:

<html>
  <head>
    <style>
      p#source span:hover
      {
        background-color: red;
      }
    </style>
    <script>
      window.onload = function () {
        var i, tx, html, node;

        node = document.getElementById("source");
        tx = node.innerHTML;

        html = "";
        for (i = 0; i < tx.length; i++)
        {
          html += "<span>" + tx.charAt(i) + "</span>";
        }

        node.innerHTML = html;
      };
    </script>
  </head>
  <body>
    <p id="source">This is an example text.</p>
  </body>
</html>
+7

.:) <span> aroungs ( ... ;)):

JQuery

<script type="text/javascript">
    $(document).ready(function() {
        var $higlightSection = $("p");

        $higlightSection.html($higlightSection.text().replace(/(\S)/g, "<span>$1</span>"));

        $higlightSection.find("span").on("hover", function() {
            $(this).toggleClass("highlight");
        });
    });
</script>

CSS

<style>
    p {cursor: default;}
    .highlight {color: red;}
</style>

EDIT: , HTML-.

+1

All Articles