search

Home  >  Q&A  >  body text

javascript - The click event of ul's li after moving in conflicts with the moving out event

As shown in the picture: The effect I want is that when the li of ul is moved in, the color changes to red, and when moved in, the color changes to blue;
But if a certain li is selected (that is, clicked), I hope that before clicking the next li , this li is always red. Even if the mouse passes through it again and the removal event is triggered, it still needs to remain red until another li is clicked.

The following is my code. The effect of this code can only be that after clicking, if the li is moved out, the color will remain blue. However, if the clicked li is moved in and out again, its color will not remain red and will become blue. .

Is there anyone who can help me solve this problem =-= Thank you in advance

<ul class="h1">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
</ul>
<script>
    $('.h1 li').mouseenter(function(){
        $(this).css({"background":"red"})
        $(this).on("click",function(){
            $('.h1 li').css({"background":"blue"})
            $(this).css({"background":"red"})
            $(this).mouseleave(function(){
                $(this).css({"background":"red"})
            })
        })
    }).mouseleave(function(){
        $(this).css({"background":"blue"})
    })
</script>
漂亮男人漂亮男人2769 days ago607

reply all(4)I'll reply

  • 为情所困

    为情所困2017-05-18 10:51:41

    Changing the position of css can achieve the effect. If you don’t believe me, try it. DEMO I will write one later when I have time.

    js just distinguishes which one you click

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-05-18 10:51:41

    You can use the style priority by visual inspection. The class added when you click is added with !important. The priority of another class added when you move in is lower than the one added when you click~

    reply
    0
  • PHPz

    PHPz2017-05-18 10:51:41

    css

    .h1 li {
        background-color: blue;
    }
    .h1 li:hover{
        background-color: red;
    }
    .chosen {
        background-color: red!important;
    }

    js:

    
    $('.h1 li').click(function() {
        $('.h1 li').removeClass('chosen');
        $(this).addClass('chosen');
    })
    

    reply
    0
  • 漂亮男人

    漂亮男人2017-05-18 10:51:41

    Thank you for the invitation.

    HTML:

    <ul class="h1">
        <li class="bl">1</li>
        <li class="bl">2</li>
        <li class="bl">3</li>
        <li class="bl">4</li>
        <li class="bl">5</li>
    </ul>

    CSS:

    .bl {
        background-color: blue;
    }
    .bl:hover{
        background-color: red;
    }
    .clk {
        background-color: red;
    }

    JavaScript:

    $('.h1>li').click(function() {
        $('.clk').removeClass('clk').addClass('bl');
        $(this).removeClass('bl').addClass('clk');
    })

    Is this so?

    reply
    0
  • Cancelreply