开发者

Jquery Toggle with Multiple Selectors

开发者 https://www.devze.com 2023-04-03 07:00 出处:网络
I have two images with different IDs, lets say #pic1 and #pic2. I tried adding both selectors to a toggle but they both toggle the same element independently, so when you click the first pic and then

I have two images with different IDs, lets say #pic1 and #pic2. I tried adding both selectors to a toggle but they both toggle the same element independently, so when you click the first pic and then the second, the second doesn't toggle the target div back it performs the first part of the toggle a second time. For instance if it's supposed to slide a 100px to the left and then slide 100px back to the right, clicking #pic1 would slide it 100px left but clicking #pic2 would just slide it 100px to the left开发者_Go百科 again. Can someone give me an idea of what direction I should be looking?

$('#pic1,#pic2').toggle(
function()
{
  $('#mylayer').delay(1000).animate({left: "+=100"});
  $('#overlay').animate({opacity: 0.8});
},
function()
{
  $('#mylayer').animate({left: "-=100"});
  $('#overlay').delay(1000).animate({opacity: 0});
});


Try something like this that keeps track of the open/closed state once for both clicks and uses jQuery's data capability to avoid using a global variable and to make this more extensible to be used multiple places:

$('#pic1,#pic2').click() {
    var mylayer = $("#mylayer");
    var open = mylayer.data("open");
    if (open) {
        mylayer.animate({left: "-=100"});
        $('#overlay').delay(1000).animate({opacity: 0});
        mylayer.data("open", false);
    } else {
        mylayer.delay(1000).animate({left: "+=100"});
        $('#overlay').animate({opacity: 0.8});
        mylayer.data("open", true);
    }
}
0

精彩评论

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