开发者

jQuery Slide Toggle help

开发者 https://www.devze.com 2023-01-08 14:49 出处:网络
I have the following code: $(\"a.sticky-link\").click(function (e) { e.preventDefault(); $(\"div.stickies-box\").slideToggle(\'slow\');

I have the following code:

$("a.sticky-link").click(function (e) {
        e.preventDefault();

        $("div.stickies-box").slideToggle('slow');
        $("a.sticky-link").toggleClass("selected");
    });开发者_如何转开发

    $("div.stickies-box").mouseup(function () {
        return false
    });
    $(document).mouseup(function (e) {
        if ($(e.target).parent("a.sticky-link").length == 0) {
            $("a.sticky-link").removeClass("selected");
            $("div.stickies-box").slideUp('slow');
        }
    });

Which basically shows and hides a div when a user clicks a button and then hides it should they click anywhere else on the page. The problem I have is if the box is already shown and the user clicks the button again (assuming they intend to hide the box) it will just quickly hide and reshow the box, when all I want it to do is hide the box.

Also instead of sliding can the effect be changed to actually moving up and down as the slide effect looks more like a wipe.

Thanks.


The main problem is that your mouseup event will fire before the click event on the <a>.

You can detect that your mouseup event isn't occuring on the a.sticky-link or the div.stickies-box before hiding the box:

$("a.sticky-link").click(function (e) {
    e.preventDefault();

    $("div.stickies-box").slideToggle('slow');
    $("a.sticky-link").toggleClass("selected");
});

$(document).mouseup(function (e) {
    var $targ = $(e.target);
    // if we are the link or the box, exit early
    if ($targ.is('a.sticky-link') || $targ.is('div.stickies-box')) return; 
    // if we have a parent who is either, also exit early
    if ($targ.closest('a.sticky-link,div.stickies-box').length) return;

    // hide the box, unselect the link
    $("a.sticky-link").removeClass("selected");
    $("div.stickies-box").slideUp('slow');
});


I was just thinking about it, and will be deleting my other answer if this one ends up working...

You might be able to just stopPropagation() on the mouseup events, replace the one you currently have for div.stickies-box with this:

$("div.stickies-box,a.sticky-link").mouseup(function (e) {
  e.stopPropagation();
});


see-

http://api.jquery.com/slideToggle/

http://api.jquery.com/toggle/

0

精彩评论

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