How do you change the style of a few elements, except the current one?



  • There's a group of elements. How do you make a mouse on one? div Did the others change their meaning?

    I want to do this on a clean JavaScript without jQuery. Please give me an example of the function.



  • var blocks = document.querySelectorAll('.block');
    

    document.getElementById('bl').addEventListener('mouseenter', function() {
    Array.prototype.forEach.call(blocks, function(el) {
    el.innerText = Math.floor(Math.random() * 10);
    });
    });

    .block {
    width: 100px;
    height: 50px;
    border: 1px solid black;
    }
    .sel {
    background: #aaa;
    }
    <div class="block sel" id="bl">1</div>
    <div class="block">2</div>
    <div class="block">3</div>
    <div class="block">4</div>


    Update after comment

    In order to capture the events of all blocks, it is possible to:

    var blocks = document.querySelectorAll('.block');

    document.body.addEventListener('mouseover', function(e) {
    var bg = 'red';
    if (!e.target.classList.contains('block')) {
    bg = '';
    }
    Array.prototype.forEach.call(blocks, function(el) {
    if (el !== e.target)
    el.style.background = bg;
    else
    el.style.background = '';
    });
    });

    .block {
    width: 100px;
    height: 50px;
    border: 1px solid black;
    }
    <div class="block" id="bl">1</div>
    <div class="block">2</div>
    <div class="block">3</div>
    <div class="block">4</div>


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2