how to highlight a div for a few seconds using jQuery

前端 未结 5 2217
無奈伤痛
無奈伤痛 2021-02-08 01:04

I want to be add the following to a a page:

When a div is clicked, I want to:

  1. change the background color of the clicked on div for a few seconds
相关标签:
5条回答
  • 2021-02-08 01:39

    One way is to go about like this using setTimeout:

    $(function () {
        $('div.highlightable').click(function () {
            $(this).addClass('highlighted');
            setTimeout(function () {
                $('div.highlightable').removeClass('highlighted');
            }, 2000);
        });
    });
    
    0 讨论(0)
  • 2021-02-08 01:40

    I think you are looking for the Highlight effect.

    http://docs.jquery.com/UI/Effects/Highlight

    0 讨论(0)
  • 2021-02-08 01:42

    For posterity, here is an answer involving the jQuery queue() function.

    $('.menul').addClass('red').delay(1000).queue(function(next){
       $(this).removeClass('red');
       next();
    });
    

    From: https://forum.jquery.com/topic/inserting-a-delay-between-adding-and-removing-a-class#14737000002257187

    0 讨论(0)
  • 2021-02-08 01:49

    You can use the jQuery UI's Highlight Effect:

    $(".myDiv").effect("highlight", {}, 3000);
    

    Demo in Stack Snippets:

    $(function() {
    
      $(".myDiv").click(function() {
        $(this).effect("highlight", {}, 3000);
      });
    
    });
    .myDiv {
      margin: 0px;
      width: 100px;
      height: 80px;
      background: #666;
      border: 1px solid black;
      position: relative;
    }
    <link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet" type="text/css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
    
    
    <div class="myDiv"></div>

    0 讨论(0)
  • 2021-02-08 01:50

    You could use the setTimeout function:

    $('div.highlightable').click(function(){
        var $this = $(this);
        //change background color via CSS class
        $this.addClass('highlighted');
        // set a timeout that will revert back class after 5 seconds:
        window.setTimeout(function() {
            $this.removeClass('highlighted');
        }, 5 * 1000);
    });
    
    0 讨论(0)
提交回复
热议问题