开发者

jQuery If statements and variables

Basically, I have a top bar that scrolls down when hovered on. I added a top mask layer to make it darker. I want the top mask to be visible when css top开发者_运维问答 value is = -180.

The current problem should be that the variable (css top value) is not updating all the time.

$('.topmask').hover(function () {
    $('.topbar').stop().animate({"top":"0px"});
    visible1 = $('.topbar').css('top');
});

$('.topbar').mouseleave(function () {
    $(this).stop().animate({"top":"-180px"});
});

var visible1 = $('.topbar').css('top');;console.log(visible1);
var visible = parseFloat(visible1); 

if (visible = -180) {
    $('.topmask').show();
} else {
    $('.topmask').hide();
}

And here's a link to a JSfiddle I quickly did to demonstrate the problem better, as I am obviously bad at explaining. http://jsfiddle.net/Fregos/DyrK5/


Animations execute asynchronously, so when you're calculating the top, the animation hasn't yet completed. How about showing and hiding the topbar based on a callback fired after the animation is complete?

$('.topmask').hover(function () {
    $('.topbar').stop().animate({"top":"0px"}, function() {
        $('.topmask').hide('fade');
    });
});

$('.topbar').mouseleave(function () {
    $(this).stop().animate({"top":"-180px"}, function() {
        $('.topmask').show('fade');
    });
});

Working example at http://jsfiddle.net/DyrK5/1/.


There are quite a few problems I see here. First and foremost, you must set the action to either show or hide the mask as a callback of the animation function. Here's what happens when the page first loads for you:

  1. If a user hovers on topbar, perform an animation.
  2. If a user stops hovering on topbar, perform an animation.
  3. If topbar's position is -180px, show the mask. Otherwise, hide it.

What you really want is this:

  1. If a user hovers on topbar, perform an animation. At the conclusion of the animation, hide the mask.
  2. If a user stops hovering on topbar, perform an animation. At the conclusion of the animation, show the mask.

So either you need to conditionally hide or show the mask within the bound event or within the animation callback. For more information on setting a callback to the animate function, take a look at this: http://api.jquery.com/animate/

The other noticeable glaring error I see is that you are currently setting the value of visible to -180 in your conditional statement.

if (visible = -180) { ... }

is not the same as:

if (visible == -180) { ... }


Why not just do:

$('.topmask').hover(function () {
    $('.topbar').stop().animate({"top":"0px"});
    $('.topmask').hide();
});
$('.topbar').mouseleave(function () {
    $(this).stop().animate({"top":"-180px"}, function() {
        $('.topmask').show();
    });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜