Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Две галереи jquery на одной странице (https://javascript.ru/forum/misc/57634-dve-galerei-jquery-na-odnojj-stranice.html)

polearmik 12.08.2015 17:31

Две галереи jquery на одной странице
 
Добрый день,
Пытаюсь прикрутить галерею к своему сайту, нашел в целом удовлетворяющий меня jquery скрипт (http://coderpro.ru/prostaya-galereya-na-jquery.html) проблема в том что при размещении двух и более подобных галерей на одной странице, скрипт работает некорректно.
Понимаю что нужно сделать чтобы поиск и смена картинок производился только в определенном div блоке, а не по всей странице, пытался сам поправить но, не выходит, маловато знаний. Подскажите знающие люди? ;)
Рабочий пример с 1 галереей - http://jsfiddle.net/x7ess5zd/
Не корректно рабочий пример с 2 галереями - http://jsfiddle.net/d5op9mao/

рони 12.08.2015 20:32

простейшая галерея на jquery
 
polearmik,

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title> - jsFiddle demo</title>
  <script type='text/javascript' src='http://code.jquery.com/jquery-2.1.3.js'></script>
  <style type='text/css'>
    .gallery-box{
  width:600px;
  padding:25px 0 0;
  margin:0 auto;
}
.view{
  position:relative;
  margin:0 0 5px;
}
.big-image img{
  display:block;
  width:300px;
  height:150px;
}
.prev, .next{
  position:absolute;
  width:40px;
  height:40px;
}
.prev{
  bottom:20px;
  left:20px;
  background:url(http://coderpro.ru/images/images/controls.png) no-repeat 0 0;
}
.next{
  bottom:20px;
  left:250px;
  background:url(http://coderpro.ru/images/images/controls.png) no-repeat -48px 0;
}

.thumbnails{
  width:605px;
}
.thumbnails a{
  float:left;
  margin:0 5px 0 0;
}
.thumbnails a img{
  width:70px;
  height:39px;
  border: 2px solid transparent;
  display:block;
}
.thumbnails .active img{
  border-color:#069;
}
  </style>
<script>
$(function() {
    function a(c, d, a, f) {
        var e = c.length,
            b = 0;
        c.each(function(g, a) {
            $("img", a).on("click", function(e) {
                e.preventDefault();
                b = g;
                //d.src = this.src;
$(d).stop().animate({opacity: 0}, 400, function() {
         d.src = a.href; $(d).animate({opacity: 1}, 400);
});
                c.removeClass("active");
                $(a).addClass("active")
            })
        });
        a.click(function(a) {
            a.preventDefault();
            b--;
            b < 0 && (b = e - 1);
            $("img", c.eq(b)).click()
        });
        f.click(function(a) {
            a.preventDefault();
            b++;
            b %= e;
            $("img", c.eq(b)).click()
        })
    }
    $(".gallery-box").each(function(c, d) {
        a($(".thumbnails a", d), $(".big-image img", d)[0], $(".prev", d), $(".next", d))
    })
});
</script>

</head>
<body>
  <div class="gallery-box">
    <div class="view">
        <div class="big-image"><img src="http://coderpro.ru/images/images/img11.jpg" alt="image11"></div>
        <a href="#" class="prev"></a>
        <a href="#" class="next"></a>
    </div>

    <div class="thumbnails">
        <a href="http://coderpro.ru/images/images/img11.jpg" class="active">
        <img src="http://coderpro.ru/images/images/img11.jpg" alt="image11"></a>
        <a href="http://coderpro.ru/images/images/img12.jpg"><img src="http://coderpro.ru/images/images/img12.jpg" alt="image12"></a>
        <a href="http://coderpro.ru/images/images/img13.jpg"><img src="http://coderpro.ru/images/images/img13.jpg" alt="image13"></a>
        <a href="http://coderpro.ru/images/images/img14.jpg"><img src="http://coderpro.ru/images/images/img14.jpg" alt="image14"></a>
    </div>
</div>
<div class="gallery-box">
    <div class="view">
        <div class="big-image"><img src="http://xsaxs.ru/wall/30/megapolis_vecher_neboskreby_tuman_prev.jpg" alt="image11"></div>
        <a href="#" class="prev"></a>
        <a href="#" class="next"></a>
    </div>

    <div class="thumbnails">
        <a href="http://xsaxs.ru/wall/30/megapolis_vecher_neboskreby_tuman_prev.jpg" class="active">
            <img src="http://xsaxs.ru/wall/30/megapolis_vecher_neboskreby_tuman_prev.jpg" alt="image11"></a>
        <a href="http://www.desktophdwallpapers.eu/thumbs/hong-kong-t2.jpg"><img src="http://www.desktophdwallpapers.eu/thumbs/hong-kong-t2.jpg" alt="image12"></a>
        <a href="http://www.kartinki.me/mini/201209/7562.jpg"><img src="http://www.kartinki.me/mini/201209/7562.jpg" alt="image13"></a>
        <a href="https://im2-tub-ru.yandex.net/i?id=f089c3a82a9415434bf21a96b70fce5d&n=33&h=170"><img src="https://im2-tub-ru.yandex.net/i?id=f089c3a82a9415434bf21a96b70fce5d&n=33&h=170" alt="image14"></a>
    </div>
</div>

</body>

</html>

рони 13.08.2015 02:02

простейшая галерея на jquery
 
polearmik,
:) большое фото из href
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title> - jsFiddle demo</title>
  <script type='text/javascript' src='http://code.jquery.com/jquery-2.1.3.js'></script>
  <style type='text/css'>

  body{
    height: 500px;
     background-color: #8900EB;
  }

    .gallery-box{
  width:300px;
  padding:25px 0 0;
  margin:0 auto;
}
.view{
  position:relative;
  margin:0 0 5px;
}
.big-image img{
  border-radius: 12px;
  border: 2px solid #FFF;
  display:block;
  width:100%;
  height: 150px;
}
.prev, .next{
  position:absolute;
  width:20px;
  height:20px;

}
.prev{
  bottom:20px;
  left:20px;
  background:url(http://coderpro.ru/images/images/controls.png) no-repeat 0 0;
  background-size: cover;
}
.next{
  bottom:20px;
  left:265px;
  background:url(http://coderpro.ru/images/images/controls.png) no-repeat -24px 0;
  background-size: cover;
}

.thumbnails{
   display: flex;
   flex-wrap: wrap;
   width:100%;
}
.thumbnails a{
  width:24%;
  flex:1;
  margin:4px;
  padding: 0;
}
.thumbnails a img{
  width:100%;
  height:39px;
  border-radius: 5px;
  border: 1px solid #D2691E;
}
.thumbnails .active img{
  border-color:#FFF;
   border-width:  2px;
}
  </style>
<script>
$(function() {
    function Itr(source, indx, loop, fn) {
        this.source = source;
        this.len = source.length - 1;
        this.loop = loop;
        this.indx = indx || 0;
        this.fn = fn
    }
    Itr.prototype.next = function() {
        return this.change(1)
    };
    Itr.prototype.prev = function() {
        return this.change(-1)
    };
    Itr.prototype.current = function() {
        return this.fn ? this.fn(this.source[this.indx]) : this.source[this.indx]
    };
    Itr.prototype.change = function(a) {
        this.indx += a;
        this.indx > this.len && (this.loop ? this.indx = 0 : this.indx = this.len);
        this.indx < 0 && (this.loop ? this.indx = this.len : this.indx =
            0);
        return this.current()
    };
    Itr.prototype.setIndex = function(a) {
        this.indx = a;
        return this.current()
    };
    Itr.prototype.changeLoop = function(a) {
        this.loop = !this.loop;
        return this.current()
    };

    function a(links, big, prev, next) {
        var fn = new Itr(links, 2, true, function(a) {
            big.src = a.href;
            links.removeClass("active");
            $(a).addClass("active")
        });
        links.each(function(g, a) {
            $("img", a).on("click", function(e) {
                e.preventDefault();
                fn.setIndex(g)
            })
        });
        prev.click(function(a) {
            a.preventDefault();
            fn.prev()
        });
        next.click(function(a) {
            a.preventDefault();
            fn.next()
        });
        fn.current()
    }
    $(".gallery-box").each(function(c, d) {
        a($(".thumbnails a", d), $(".big-image img", d)[0], $(".prev", d), $(".next", d))
    })
});
</script>

</head>
<body>
  <div class="gallery-box">
    <div class="view">
        <div class="big-image"><img src="" alt="image11"></div>
        <a href="#" class="prev"></a>
        <a href="#" class="next"></a>
    </div>

    <div class="thumbnails">
    <a href="https://js.cx/gallery/img2-lg.jpg" title="Image 2"><img src="https://js.cx/gallery/img2-thumb.jpg"></a>
    <a href="https://js.cx/gallery/img3-lg.jpg" title="Image 3"><img src="https://js.cx/gallery/img3-thumb.jpg"></a>
    <a href="https://js.cx/gallery/img4-lg.jpg" title="Image 4"><img src="https://js.cx/gallery/img4-thumb.jpg"></a>
    <a href="https://js.cx/gallery/img5-lg.jpg" title="Image 5"><img src="https://js.cx/gallery/img5-thumb.jpg"></a>
    <a href="https://js.cx/gallery/img6-lg.jpg" title="Image 6"><img src="https://js.cx/gallery/img6-thumb.jpg"></a>

    </div>
</div>
<div class="gallery-box">
    <div class="view">
        <div class="big-image"><img src="" alt="image11"></div>
        <a href="#" class="prev"></a>
        <a href="#" class="next"></a>
    </div>

    <div class="thumbnails">
        <a href="http://xsaxs.ru/wall/30/megapolis_vecher_neboskreby_tuman_prev.jpg">
            <img src="http://xsaxs.ru/wall/30/megapolis_vecher_neboskreby_tuman_prev.jpg" alt="image11"></a>
        <a href="http://www.desktophdwallpapers.eu/thumbs/hong-kong-t2.jpg"><img src="http://www.desktophdwallpapers.eu/thumbs/hong-kong-t2.jpg" alt="image12"></a>
        <a href="http://www.kartinki.me/mini/201209/7562.jpg"><img src="http://www.kartinki.me/mini/201209/7562.jpg" alt="image13"></a>
        <a href="https://im2-tub-ru.yandex.net/i?id=f089c3a82a9415434bf21a96b70fce5d&n=33&h=170"><img src="https://im2-tub-ru.yandex.net/i?id=f089c3a82a9415434bf21a96b70fce5d&n=33&h=170" alt="image14"></a>
    </div>
</div>

</body>

</html>

polearmik 13.08.2015 14:42

Благодарю за помощь!! :thanks:
Все прекрасно работает, выручили.

polearmik 13.08.2015 20:31

рони,
Чуть попытался доработать ваш пример, для более плавного перехода между изображениями, вот что вышло http://jsfiddle.net/d5op9mao/1/. Изображение исчезает и появляется у двух галерей, а меняется только в той где нажимаешь. Хотелось бы поправить :)
И не вышло сделать такой же плавные переход при нажатии на миниатюру, сможете подсказать?

рони 13.08.2015 20:49

polearmik,
менять надо
только одну строку d.src = this.src;
на
$(d).stop().animate({opacity: 0}, 400, function() {
         d.src = a.href; $(d).animate({opacity: 1}, 400);
});

смотрите пост 2 снова строка 064 - условие для простоты: большое фото хранится в href

в 3 посте менять строку 107 соответственно названиям переменных
этот же код

polearmik 14.08.2015 09:19

рони,
Низкий поклон вам!! :thanks:
Работает все так как хотел)

polearmik 17.08.2015 18:27

рони,
Прошу прощения но снова требуется ваша помощь, надеюсь что этот раз последний. Вот мой вариант галереи http://jsfiddle.net/d5op9mao/3/, по сути сама галерея спрятана в модальном окне и вызывается по клику на соответствующую ссылку, все отлично работает за исключением одного но, если на главной странице сменить на вторую картинку и нажать вызов модального окна то в модальном окне будет первая картинка и первая миниатюра будет с классом "active", а хотелось бы что если на главной странице производилась смена картинки то и в модальном окне происходила так же смена на второе изображение и вторая миниатюра была с классом "active". Надеюсь понятно изложил :)
Есть вариант как поправить?

рони 17.08.2015 19:00

polearmik,
вы бы подумали над алгоритмом без setTimeout
http://jsfiddle.net/d5op9mao/4/

polearmik 17.08.2015 22:50

И снова спасибо, по поводу алгоритма переписал, так будет правильней?
$(function(){
$('.nizimage a').click(function(){ 
event.preventDefault();
 var i = $('.nizimage a').index(this);
      $('.thumbnails img').eq(i).click();    
    
var images = $(this).find('img');
var imgSrc = $(this).attr('href');
 if ($('.headimage').attr('src') == imgSrc) {}
else
{
$('.headimage').animate({opacity: 0}, 300,
 function(){
$(".headimage img").attr({ src: imgSrc });
$('.headimage').animate({opacity: 1}, 300);
});
}
return false;
});
})


Часовой пояс GMT +3, время: 12:51.