简体   繁体   中英

Hover CSS with JQuery

I want to edit the rendering of an element when hovering. To achieve this, I created a button and I want the first click to set the hover rendering and the second click to reset the hover rendering. Currently, the hover style appears even when I'm not on the div :

$("#editer-script").click(function() {
  var clicks = $(this).data('clicks');

  if (clicks) {
    $('.contenu-editable').mouseover(function(){
        $('.contenu-editable').css("background-color", "transparent");
        $('.contenu-editable .fa.fa-pencil').css("display", "none");
    });
    $("#editer-script").text('Rendre éditable');
  } else {
    $('.contenu-editable').mouseover(function(){
        $('.contenu-editable').css("background-color", "#f4f6f9");
        $('.contenu-editable .fa.fa-pencil').css("display", "inline-block");
    });
    $("#editer-script").text('Ne pas rendre éditable');
  }

  $(this).data("clicks", !clicks);
});

Thank you in advance for your help.

I would use two different css classes. One default and one for the change of the hover effects. And then just toggle the second class on click of the button element.

It's mutch easier than try to do it your way and it could be easily changed and extended just in css. No need to touch the script in the future.

 $("#editer-script").click(function() { var clicks = $(this).data('clicks'); $('.contenu-editable').toggleClass('special', !clicks); $("#editer-script").text(clicks ? 'Rendre éditable' : 'Ne pas rendre éditable'); $(this).data("clicks", !clicks); }); 
 .contenu-editable:hover { background-color: transparent; } .contenu-editable:hover .fa.fa-pencil { display: none; } .contenu-editable.special:hover { background-color: #f4f6f9; } .contenu-editable.special:hover .fa.fa-pencil { display: inline-block; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="editer-script">Rendre éditable</button> <div class="contenu-editable"> <i class="fa fa-pencil">pencil</i> content </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM