jQuery基于视口大小悬停动画

时间:2013-11-25 22:51:03

标签: javascript jquery

在学习更多jQuery的过程中遇到了一些代码问题。 当用户将鼠标悬停在特定元素上时,我试图获得动画效果(fadeIn / fadeOut)。

但是,当视口调整大小时,即移动显示的480px以下,我需要忽略悬停效果,只显示号召性用语。在我的下面的代码中,我试图检测视口,然后通过if-then-else语句应用适当的脚本。

我怀疑我没有正确地嵌套东西或者有错误的分号。我一直在盯着这一段时间而被困住了。

我确实将这些其他帖子作为参考。

如果您有任何疑问或可以提供其他详细信息,请与我们联系。

// Script to display div call-to-action over logos

var detectViewPort = function(){
    var viewPortWidth = $(window).width();

// if its bigger than 480px then do the hover effect
    if (viewPortWidth > 480){

// On mouse over logo
    $('.unionlogo').hover(function() {              

// Display the call to action
        $(this).find('a.calltoaction').stop(false,true).fadeIn(400);
        $(this).find('p.union-name').stop(false,true).fadeOut(400);
    },
    function() {

// Hide the call to action
        $(this).find('a.calltoaction').stop(false,true).fadeOut(400);
        $(this).find('p.union-name').stop(false,true).fadeIn(400);
    });
// if its smaller than 480px then just show the call-to-action
}else{
    $('a.calltoaction').show();
};

$(function(){
  detectViewPort();
});

$(window).resize(function () {
   detectViewPort();
});

2 个答案:

答案 0 :(得分:0)

也许尝试向CSS添加媒体查询以隐藏原始按钮,并在视口为480px或更低时添加号召性用语按钮。

答案 1 :(得分:0)

您是否在控制台中查看错误消息是什么?正如你所说,你离开了一个支架。你应该更好地格式化你的代码,这很明显。

var detectViewPort = function(){
    var viewPortWidth = $(window).width();

    // if its bigger than 480px then do the hover effect
    if (viewPortWidth > 480){

        $('a.calltoaction').hide();
        // On mouse over logo
        $('.unionlogo').off('mouseenter mouseleave');
        $('.unionlogo').hover(function() {              
            // Display the call to action
            $(this).find('a.calltoaction').stop(false, true).fadeIn(400);
            $(this).find('p.union-name').stop(false, true).fadeOut(400);
        }, function() {
            // Hide the call to action
            $(this).find('a.calltoaction').stop(false, true).fadeOut(400);
            $(this).find('p.union-name').stop(false, true).fadeIn(400);
        });
        // if its smaller than 480px then just show the call-to-action
    } else {
        $('.unionlogo a.calltoaction').stop(false,true).fadeOut(400);
        $('.unionlogo p.union-name').stop(false,true).fadeIn(400);
        $('a.calltoaction').show();
        // un bind the hover incase of browser resize
        $('.unionlogo').off('mouseenter mouseleave');


    };
}

$(function(){
    $(document).ready(function(){
        detectViewPort();
    });
});

$(window).resize(function () {
   detectViewPort();
});