JQuery UI (effects core) addClass/removeClass on one element with multiple selectors…but there's a catch

浪子不回头ぞ 提交于 2019-12-23 16:27:31

问题


Thanks for taking a look. I'm trying to used the jQ UI addClass / remove Class methods to expand an hr element upon clicking preceding sibling divs. jQ UI effects core enables smooth animated transition between two classes: http://jqueryui.com/demos/removeClass/. Additionally, hr must be added dynamically with $ to achieve the broader site design.

Here are the pieces of the puzzle:

  1. My code renders rows of four 100x100px sibling divs. These divs don't have classes, but FEEL FREE TO ADD THEM IF IT HELPS -- each div will eventually have a unique class. After every 4th div, there's a dynamically added hr.
  2. Upon clicking any given div, the immediate next hr must toggle to the class "open", which causes the row to expand. If this div is then clicked again, it must toggle/remove the class "open" from hr, causing the hr the shrink to it's original size.
  3. If one div is clicked to expand a hr and then another div is clicked, two animations must be triggered: first, the "open" class must be removed, causing the row to shrink back down, and THEN the class must be re-added to reopen the row. However, if, for example, a div is clicked to open the second row, and then a second div preceding the first hr is clicked, this action must first close the second hr and then open the second div's corresponding hr.

I'm stuck. I've tried a number of jQ function combos, but the results are whacky. What you see is the closest I've gotten. Thanks for giving this one a shot. Feel free to add to the code however you can to get this working.

<!--HTML...the children divs of ".main" can have their own unique classes if that helps-->
<div class="main">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</div>

/*CSS-some of this creates other events not mentioned above. These are simplified versions of what I need for my final site design*/

.main  {
    width: 450px;
}
.main div {
    height: 100px;
    width: 100px;
    background-color: #000;
    margin: 3px;
    float:left;
}
div.select   {
    background-color: #f00;
    border: 2px solid #00F;
    margin: 3px;
    float:left;
    display: block;
}
div.active   {
    background-color: #f00;
    margin: 3px;
    float:left;
    display: block;
}
hr  {
    background-color: #FF0;
    float: left;
    display: block;
    height: 20px;
    width: 450px;
}
hr.open {
    float: left;
    display: block;
    height: 300px;
    width: 450px;

}

/*the JS - sorry about the double quotes.  I'm using Dreamweaver, which seems to add them to everything*/

$(document).ready(function() {
//dynamcally adds the <hr> after every 4th div.
    $(".main div:nth-child(4n)").after('<hr class="closed"></hr>');
//puts a blue border on the squares
    $('.main div').hover(function()  {
        $(this).addClass('select');
    },
    function() {
        $(this).removeClass('select')
    });
//changes the color of the active square to red and "deactivates" the previous one.
    $('.main div').click(function()  {
        $(this).toggleClass('active').siblings().removeClass('active');
    });
//here in lies the problem...???
    $('.main div').click(function()  {
        $('hr').removeClass('open', 1000);
        $(this).toggle
        (function() {
            $(this).nextAll("hr").first().addClass('open', 500);
        },
        function()  {
            $(this).nextAll("hr").first().removeClass('open', 500)
        });

    });
});

回答1:


I am pretty sure that this is what you want, I copied the general HTML layout from http://makr.com (you mentioned that that was what you wanted):

Demo: http://jsfiddle.net/SO_AMK/xm7Sk/

jQuery:

$(".main article:nth-child(4n)").after('<hr class="split"></hr>');
$(".main > article .slidedown").click(function(e) {
        e.stopPropagation();
}); // If you click on the slidedown, it won't collapse

var canAnimate = true,
    slideIsOpen = false,
    animateSpeed = 1000;

$(".main > article").hover(function() {
    $(this).addClass("hover");
}, function() {
    $(this).removeClass("hover");
}).click(function() {
    if (canAnimate) {
        canAnimate = false;
        var article = $(this),
            isThisOpen = article.hasClass("active");
        if (isThisOpen) {
            $(".main").queue(function () {
                hideSlide($(this))
            });
        }
        else {
            if (slideIsOpen) {
                $(".main").queue(function () {
                    hideSlide($(this));
                }).queue(function () {
                    positionPage(article, $(this));
                }).queue(function () {
                    showSlide(article, $(this));
                }).queue(function () {
                    positionPage(article, $(this));
                });
            }
            else {
                $(".main").queue(function () {
                    positionPage(article, $(this));
                }).queue(function () {
                    showSlide(article, $(this));
                }).queue(function () {
                    positionPage(article, $(this));
                });
            }
        }
    }
});

function showSlide(elm, main) {
        canAnimate = false;
        slideIsOpen = true;
        elm.nextAll("hr.split").first().addClass("active", animateSpeed);

        elm.children(".slidedown").css("top", (elm.offset().top + 114)).addClass("active").slideToggle(animateSpeed);

        elm.addClass("active");
        main.dequeue();
        canAnimate = true;
}

function hideSlide(main) {
        canAnimate = false;
        $(".main article.active").nextAll("hr.split.active").removeClass("active", animateSpeed);

        $(".main article.active").children(".slidedown").removeClass("active").slideToggle(animateSpeed);

        $(".main article.active").removeClass("active");
        $(main).dequeue();
        canAnimate = true;
        slideIsOpen = false;
}

function positionPage(elm, main) {
    canAnimate = false;
    var body;
    if ($.browser.safari) {
        body = $("body");
    }
    else {
        body = $("html");
    }
    var elmTop = elm.offset().top,
        bodyScroll = body.scrollTop();
    if (bodyScroll - elmTop == 0) {
        var speed = 0;
    }
    else {
        var speed = animateSpeed;
    }
    body.animate({
        scrollTop: elmTop
    }, speed, function () {
        main.dequeue();
        canAnimate = true;
    })
}​

This may seem like a large script for something so small but it has some fail-safes. The only bug is, if you start clicking quickly during transitions sometimes the queues end up in the wrong order. But, the average user doesn't click quickly during animations :D




回答2:


Try this on for size: http://jsfiddle.net/Bv57T/3/

Main changes:

  1. You had 2 .click bindings to the same selector $('.main div'). This is technically supported, I believe, but there's no reason for it and it makes your code a lot harder to follow.
  2. .toggle() doesn't take functions as parameters. Check the documentation for it; it's not like hover().
  3. There's no reason to have separate functions for the add and remove. You're also removing classes twice. Were you wanting the next HR to animate open and stay open? Or wanting it to open and close immediately? If the latter, there's no reason for this line $('hr').removeClass('open', 1000);. If the former, there's no reason for the second function() with $(this).nextAll("hr").first().removeClass('open', 500) in it.

Here's the javascript I used in the fiddle

$(document).ready(function() {
    //dynamcally adds the <hr> after every 4th div.
    $(".main div:nth-child(4n)").after('<hr class="closed"></hr>');
    //puts a blue border on the squares
    $('.main div').hover(
        function()  {
            $(this).addClass('select');
        },
        function() {
            $(this).removeClass('select')
    });
    //changes the color of the active square to red and "deactivates" the previous one.
    $('.main div').click(function()  {
        $('hr.open').removeClass('open', 1000);
        if(!$(this).hasClass('active')) {
           $(this).nextAll("hr").first().addClass('open', 500);
        }
        $(this).toggleClass('active').siblings().removeClass('active');
    });
});​

If that's not exactly what you want and can't figure it out from here, go ahead and post back and I can take another crack at it.

Edit New and improved version: http://jsfiddle.net/Bv57T/4/ Updated the js above as well.

It's still possible to fake it out if you click on a second div while an animation is ongoing. You could get around that by setting a (global) bool to true for the duration of an animation and checking it before starting the next animation.

But the root of the problem is that you're trying to have the state of the UI (DOM, in other words) double up as the state of the application. This can get really hairy with even simple operations (as well you've seen). My preferred approach for things like this is to use a library that separates the UI from the application. These are usually referred to as MVC (model-view-controller) or MVVM (model-view-viewmodel - a moniker I hate because it feels intentionally confusing). My favorite is knockout.js. It's fully compatible with jQuery and jQuery UI; check out this example: animated transitions.

There are more such libraries. Backbone.js is one, knockback.js combines knockout and backbone. I know I'm forgetting some other popular & good ones...



来源:https://stackoverflow.com/questions/12487937/jquery-ui-effects-core-addclass-removeclass-on-one-element-with-multiple-selec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!