将点击代码转换为悬停代码

时间:2014-01-14 07:03:29

标签: javascript

当鼠标悬停时,如何更改以下菜单代码以打开/关闭,而不是在点击鼠标时?

var w = 0;

$('.slide').children().each(function () {
    w += $(this).outerWidth();
});

$('.outer').width(w + 5);
$('.wrap').width(w);
$('.slide').css('left', w);

$('.open').toggle(function () {
    $('.slide').stop().animate({
        left: 0
    });
    $(this).html('close');
}, function () {
    $('.slide').stop().animate({
        left: w
    });
    $(this).html('open');
});

请检查此Demo

在小提琴中,您可以看到动画在点击时有效。我需要让它在悬停时工作。你能帮帮忙吗?

5 个答案:

答案 0 :(得分:1)

尝试使用$('。wrap')。悬停。如果$('。open')。悬停,您将无法点击导航项。

此外,您可以创建另一个包装器来仅包装div.outer和a.open

$('.wrap').hover(function() {

    $('.slide').stop().animate({
        left : 0
    });

    //this is the .wrap right now
    $(this).find('a.open').html('close');

}, function() {

    $('.slide').stop().animate({
        left : w
    });

  //this is the .wrap right now
    $(this).find('a.open').html('open');
});

http://jsfiddle.net/rooseve/42sWB/2/

答案 1 :(得分:1)

使用.hover() api

试试这个

$('.open').hover(function () {

而不是

$('.open').toggle(function () {

答案 2 :(得分:1)

只是

$('.open').toggle(function() {
    $('.slide').stop().animate({
        left: 0
    });
    $(this).html('close');
}
此部分中的

只需将toggle替换为hover

答案 3 :(得分:1)

$('。open')。on('mouseenter mouseleave',function(e){

if(e.type === 'mouseleave') {
    $('.slide').stop().animate({
        left: w
    });
    $(this).html('open');
} else {
    $('.slide').stop().animate({
        left: 0
    });
    $(this).html('close');
}

});

答案 4 :(得分:0)

var w = 0;
var isVisible = false;
$('.slide').children().each(function() {
    w += $(this).outerWidth();
});

$('.outer').width(w+5);
$('.wrap').width(w);
$('.slide').css('left', w);

$('.open').on("mouseover", function() {
    if(isVisible == false) {
        $('.slide').stop().animate({
            left: 0
        });
        $(this).html('close');
        isVisible = true;
    }
    else {
        $('.slide').stop().animate({
            left: w
        });
        $(this).html('open');
        isVisible = false;
    }
});

首先,当你悬停元素时 - div将可见,直到你第二次悬停元素。

演示:http://jsfiddle.net/42sWB/3/

相关问题