如何修复下面的jquery代码

时间:2015-08-16 19:38:36

标签: jquery

<h1>Click me</h1>
<div class="content">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
    cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>

<script type="text/javascript" src="jquery-1.11.3.min.js"></script>

<script type="text/javascript">

$('.content').hide();
var $this = $('h1');``

var form = {

    enter: function(){
        console.log('slideDown')
            // $this.next('div.content').slideDown(500)     
    },

    leave: function(){
        console.log('slideUp')
            // $this.next('div.content').slideUp(500)       
    }

}

$this.mouseenter(function(){
    form.enter();
})
$this.mouseleave(function(){
    form.leave();
})
</script>
</body>

在这段代码中,我希望当我鼠标进入“点击我”时然后它会滑下&#39; .content&#39;类和鼠标离开时它会向上滑动。但是在这种情况下,当我鼠标进入时,它会一次滑动并向下滑动三次,但是当鼠标离开时它实际滑动了一次。那我该怎么办呢?请帮帮我。

2 个答案:

答案 0 :(得分:0)

您可以在执行slideDown之前检查元素是否被隐藏,并在执行slideUp之前检查它是否可见,从而多次修复动画触发。

以下是代码:

enter: function(){
    console.log('slideDown');
    if ($this.next('div.content').is(":hidden")) {
        $this.next('div.content').slideDown(500);
    }
},

leave: function(){
    console.log('slideUp');
    if ($this.next('div.content').is(":visible")) {
        $this.next('div.content').slideUp(500); 
    }
}

现场演示:

$('.content').hide();
var $this = $('h1');``

var form = {

    enter: function(){
        console.log('slideDown');
        if ($this.next('div.content').is(":hidden")) {
            $this.next('div.content').slideDown(500);
        }
    },

    leave: function(){
        console.log('slideUp');
        if ($this.next('div.content').is(":visible")) {
            $this.next('div.content').slideUp(500); 
        }
    }

}

$this.mouseenter(function(){
    form.enter();
})
$this.mouseleave(function(){
    form.leave();
})
.content {
  overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Click me</h1>
<div class="content">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
    cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>

答案 1 :(得分:0)

$('.content').hide()$('.content').slideDown()不同,因此您无法使用其中一种设置另一种状态。

尝试:       

  $('.content').slideDown();
  var $this = $('h1');`