Пользовательское динамическое слайд-шоу с JQuery - PullRequest
0 голосов
/ 25 сентября 2018

Я пытаюсь создать собственное слайд-шоу с нуля, используя в основном jQuery.Проблема, с которой я столкнулся, заключается в том, что я пытался адаптировать его для телефонов и планшетов (в целом экран меньшего размера).Поэтому моей первой мыслью было просто поменять все px на %, но это не очень хорошо сработало, и я не знаю, как подойти к этой проблеме «лучшим» способом.

Этокак это выглядит "нормально" slider Проблема возникает при изменении размера окна, тогда я получаю эту черную полосу поверх изображения.Моя цель состоит в том, чтобы размер всей коробки изменился и выглядел так, как показано выше.(это скриншот из мобильного превью с Google Chrome)

enter image description here

Вы можете проверить фрагмент кода ниже, и он показывает черную полосу непосредственно после окнамаленький.#AutoSlider{min-height: 400px;} только для того, чтобы не получить 10 пикселей в высоту.

var options = {
Image: {
        Width: "100%",
        Height: "80%",
        BackgroundColor: "black",
        SecPerSlide: "5000"
    },
    ThumbnailContainer: {
        Width: "15%",
        Height: "100%",
        RowColor: "black"
    },
    ThumbnailCell: {
        BackgroundColor: "black",
        Space: "3px",
        Width: "100%",
        Height: "15%",
        FadedEdge: "15%"
    }
}

carsGallery = [];
var container = $("#AutoSlider");
var thumbnailContainer;
var thumbnailCell;
var activeImage;
var autoCount = 1;
var stopSlider = false;
var subImageSliderPage = 0;

$(document).ready(function () {
    GetImages();
    BuildImageSlider();
    SetStyles();
    startSlider();

});

function SetStyles() {

    container.css({
        'width': options.Image.Width,
        'height': options.Image.Height,
        'max-height': '650px',
        'background-color': options.Image.BackgroundColor,
        'position': 'relative',
        'overflow': 'hidden'
    });

    thumbnailContainer.css({
        'width': options.ThumbnailContainer.Width,
        'height': options.ThumbnailContainer.Height,
        'background-color': options.ThumbnailContainer.RowColor,
        'position': 'absolute',
        'right': '0'
    });

    thumbnailCell.css({
        'width': options.ThumbnailCell.Width,
        'height': options.ThumbnailCell.Height,
        'background-color': options.ThumbnailCell.BackgroundColor,
        'margin-bottom': options.ThumbnailCell.Space
    });

    thumbnailCellImage.css({
        'max-width': '100%',
        'max-height': '100%',
        'height': '100%',
        'width': '100%'
    });

    activeImage.css({
        'max-width': '85%',
        'max-height': '100%',
        'vertical-align': 'middle'
    });

    $('.thumbnailCell img').last().css('margin-bottom', '-37px');
    $('.thumbnailCell img').last().css('margin-top', '-37px');   
}

function BuildImageSlider() {

    container.append('<div class="dragscroll" id="ThumbNail"></div>');
    thumbnailContainer = $("#ThumbNail");

    container.append('<span style="display: inline-block;height: 100%;vertical-align: middle;" class="helper"></span><img style="position: absolute; left: -15%; right: 0; bottom: 0; margin: auto;" id="ActiveImage"/>');

    for (var i = 0; i < carsGallery.length; i++) {
        thumbnailContainer.append('<div class="thumbnailCell"><span style="display: inline-block;height: 100%;vertical-align: middle;"></span><img index="' + i + '" src="' + carsGallery[i].mainImages + '"/></div>');
    }

    container.append('<div style="pointer-events: none; background-image: linear-gradient(black, rgba(1, 0, 0, 0.0)); top: 0; right: 0; position: absolute; height: 50px; width: ' + options.ThumbnailCell.FadedEdge + ';"></div>');
    container.append('<div style="pointer-events: none; background-image: linear-gradient(rgba(1, 0, 0, 0.0), black); bottom: 0; right: 0; position: absolute; height: 50px; width: ' + options.ThumbnailCell.FadedEdge + ';"></div>');
    container.prepend('<img src="/images/Icons/defforward.png" onmouseover="pauseSlider(true);" onmouseout="pauseSlider(false);" style="bottom: 50%; right: 15%; position: absolute; z-index: 100;" class="arrow" id="rightArrow"/>');
    container.prepend('<img src="/images/Icons/defback.png" onmouseover="pauseSlider(true);" onmouseout="pauseSlider(false);" style="bottom: 50%; left: 0; position: absolute; z-index: 100;" class="arrow" id="leftArrow"/>');

    activeImage = $("#ActiveImage");
    thumbnailCell = $(".thumbnailCell");
    thumbnailCellImage = $(".thumbnailCell img");
}

function GetImages() {
    for (var i = 0; i < $('.mainPhoto img').length; i++) {
        var main = $('.mainPhoto:eq(' + i + ') img').attr('src');
        var sub = getSubImages(i);
        carsGallery.push({ mainImages: main, subImages: [sub] });
    }
}

function getSubImages(main) {
    var s = [];
    $('.interior' + main).each(function (e) {
       s.push($(this).attr('src'));
    });
    return s;
}

$(document).ready(function () {

    $(".thumbnailCell img").click(function () {
        $('#ActiveImage').attr('src', $(this).attr('src'));
        autoCount = +$(this).attr('index');
    });

    $('#rightArrow').click(function () {
        if (subImageSliderPage >= carsGallery[autoCount].subImages[0].length) {
            activeImage.attr('src', carsGallery[autoCount].mainImages).stop(true, true).hide().fadeIn();
            subImageSliderPage = 0;
        }
        else {
            activeImage.attr('src', carsGallery[0].subImages[0][subImageSliderPage]).stop(true, true).hide().fadeIn();
            subImageSliderPage++;
        }          
    });

    $('#leftArrow').click(function () {

        
    });
});


function startSlider() {
    activeImage.attr('src', carsGallery[0].mainImages).stop(true, true).hide().fadeIn();
    timerId = setInterval(function () {

        if (stopSlider != true) {
            if (autoCount >= carsGallery.length - 1) {
                autoCount = 0;
            }
            activeImage.attr('src', carsGallery[autoCount].mainImages).stop(true, true).hide().fadeIn();
            autoCount++;
        }

    }, options.Image.SecPerSlide);
}

function pauseSlider(state) {
    stopSlider = state;
}
#AutoSlider{
min-height: 400px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

<div class="col-sm-12 story-for-sale sold-cars-box">
    <div class="col-sm-10 col-sm-offset-1 story-for-sale sold-cars-box">
        <div id="AutoSlider" onmouseover="pauseSlider(true);" onmouseout="pauseSlider(false);">
            <div hidden class="carImages">                
                
                <div class="mainPhoto">
                    <img src="https://cdn.motor1.com/images/mgl/7WjgW/s4/1974-lancia-stratos-hf-stradale-for-sale.jpg"/>
                </div>
                <div class="interior">
                    <img src="https://i.pinimg.com/originals/0e/91/97/0e9197574f9f55aec58af0fe5ff265bb.jpg" class="interior0" />
                </div>
                
                <div class="mainPhoto">
                    <img src="http://dmi3w0goirzgw.cloudfront.net/gallery-images/840x560/274000/600/274681.jpg"/>
                </div>
                <div class="interior">
                    <img src="https://i.pinimg.com/originals/35/39/bd/3539bdb4edefb3a862e30386b8519ea1.jpg" class="interior1" />
                </div>
                
                                <div class="mainPhoto">
                    <img src="https://cdn.motor1.com/images/mgl/7WjgW/s4/1974-lancia-stratos-hf-stradale-for-sale.jpg"/>
                </div>
                <div class="interior">
                    <img src="https://i.pinimg.com/originals/0e/91/97/0e9197574f9f55aec58af0fe5ff265bb.jpg" class="interior2" />
                </div>
                
                                <div class="mainPhoto">
                    <img src="http://dmi3w0goirzgw.cloudfront.net/gallery-images/840x560/274000/600/274681.jpg"/>
                </div>
                <div class="interior">
                    <img src="https://i.pinimg.com/originals/35/39/bd/3539bdb4edefb3a862e30386b8519ea1.jpg" class="interior3" />
                </div>
                
                                <div class="mainPhoto">
                    <img src="https://cdn.motor1.com/images/mgl/7WjgW/s4/1974-lancia-stratos-hf-stradale-for-sale.jpg"/>
                </div>
                <div class="interior">
                    <img src="https://i.pinimg.com/originals/0e/91/97/0e9197574f9f55aec58af0fe5ff265bb.jpg" class="interior4" />
                </div>
                
                <div class="mainPhoto">
                    <img src="http://dmi3w0goirzgw.cloudfront.net/gallery-images/840x560/274000/600/274681.jpg"/>
                </div>
                <div class="interior">
                    <img src="https://i.pinimg.com/originals/35/39/bd/3539bdb4edefb3a862e30386b8519ea1.jpg" class="interior5" />
                </div>
                
                                <div class="mainPhoto">
                    <img src="https://cdn.motor1.com/images/mgl/7WjgW/s4/1974-lancia-stratos-hf-stradale-for-sale.jpg"/>
                </div>
                <div class="interior">
                    <img src="https://i.pinimg.com/originals/0e/91/97/0e9197574f9f55aec58af0fe5ff265bb.jpg" class="interior6" />
                </div>
                
                                <div class="mainPhoto">
                    <img src="http://dmi3w0goirzgw.cloudfront.net/gallery-images/840x560/274000/600/274681.jpg"/>
                </div>
                <div class="interior">
                    <img src="https://i.pinimg.com/originals/35/39/bd/3539bdb4edefb3a862e30386b8519ea1.jpg" class="interior7" />
                </div>

            </div>
        </div>
    </div>
</div>

1 Ответ

0 голосов
/ 25 сентября 2018

Я добавил VerticalAlign: «top» к вашим параметрам изображения, и пиксель показывается вертикально выровненным по центру (как добавлено).Я изменил цвет фона контейнера на серый и высоту AutoSlider до 320, который вы, конечно, можете откорректировать обратно, я просто уменьшил их для целей тестирования.

Надеюсь, это поможет

var options = {
  Image: {
    Width: "100%",
    Height: "80%",
    BackgroundColor: "grey",
    SecPerSlide: "5000",
    VerticalAlign:"top",
  },
  ThumbnailContainer: {
    Width: "15%",
    Height: "100%",
    RowColor: "black"
  },
  ThumbnailCell: {
    BackgroundColor: "black",
    Space: "3px",
    Width: "100%",
    Height: "15%",
    FadedEdge: "15%"
  }
}

carsGallery = [];
var container = $("#AutoSlider");
var thumbnailContainer;
var thumbnailCell;
var activeImage;
var autoCount = 1;
var stopSlider = false;
var subImageSliderPage = 0;

$(document).ready(function() {
  GetImages();
  BuildImageSlider();
  SetStyles();
  startSlider();

});

function SetStyles() {

  container.css({
    'width': options.Image.Width,
    'height': options.Image.Height,
    'max-height': '650px',
    'background-color': options.Image.BackgroundColor,
    'vertical-align': options.Image.VerticalAlign,
    'position': 'absolute',
    'overflow': 'hidden'
  });

  thumbnailContainer.css({
    'width': options.ThumbnailContainer.Width,
    'height': options.ThumbnailContainer.Height,
    'background-color': options.ThumbnailContainer.RowColor,  
    'position': 'absolute',
    'right': '0'
  });

  thumbnailCell.css({
    'width': options.ThumbnailCell.Width,
    'height': options.ThumbnailCell.Height,
    'background-color': options.ThumbnailCell.BackgroundColor,
    'margin-bottom': options.ThumbnailCell.Space
  });

  thumbnailCellImage.css({
    'max-width': '100%',
    'max-height': '100%',
    'height': '100%',
    'width': '100%'
  });

  activeImage.css({
    'max-width': '85%',
    'max-height': '100%',
    'top': 0,
  });

  $('.thumbnailCell img').last().css('margin-bottom', '-37px');
  $('.thumbnailCell img').last().css('margin-top', '-37px');
}

function BuildImageSlider() {

  container.append('<div class="dragscroll" id="ThumbNail"></div>');
  thumbnailContainer = $("#ThumbNail");

  container.append('<span style="display: inline-block;height: 100%;vertical-align: middle;" class="helper"></span><img style="position: absolute; left: -15%; right: 0; bottom: 0; margin: auto;" id="ActiveImage"/>');

  for (var i = 0; i < carsGallery.length; i++) {
    thumbnailContainer.append('<div class="thumbnailCell"><span style="display: inline-block;height: 100%;vertical-align: middle;"></span><img index="' + i + '" src="' + carsGallery[i].mainImages + '"/></div>');
  }

  container.append('<div style="pointer-events: none; background-image: linear-gradient(black, rgba(1, 0, 0, 0.0)); top: 0; right: 0; position: absolute; height: 50px; width: ' + options.ThumbnailCell.FadedEdge + ';"></div>');
  container.append('<div style="pointer-events: none; background-image: linear-gradient(rgba(1, 0, 0, 0.0), black); bottom: 0; right: 0; position: absolute; height: 50px; width: ' + options.ThumbnailCell.FadedEdge + ';"></div>');
  container.prepend('<img src="/images/Icons/defforward.png" onmouseover="pauseSlider(true);" onmouseout="pauseSlider(false);" style="bottom: 50%; right: 15%; position: absolute; z-index: 100;" class="arrow" id="rightArrow"/>');
  container.prepend('<img src="/images/Icons/defback.png" onmouseover="pauseSlider(true);" onmouseout="pauseSlider(false);" style="bottom: 50%; left: 0; position: absolute; z-index: 100;" class="arrow" id="leftArrow"/>');

  activeImage = $("#ActiveImage");
  thumbnailCell = $(".thumbnailCell");
  thumbnailCellImage = $(".thumbnailCell img");
}

function GetImages() {
  for (var i = 0; i < $('.mainPhoto img').length; i++) {
    var main = $('.mainPhoto:eq(' + i + ') img').attr('src');
    var sub = getSubImages(i);
    carsGallery.push({
      mainImages: main,
      subImages: [sub]
    });
  }
}

function getSubImages(main) {
  var s = [];
  $('.interior' + main).each(function(e) {
    s.push($(this).attr('src'));
  });
  return s;
}

$(document).ready(function() {

  $(".thumbnailCell img").click(function() {
    $('#ActiveImage').attr('src', $(this).attr('src'));
    autoCount = +$(this).attr('index');
  });

  $('#rightArrow').click(function() {
    if (subImageSliderPage >= carsGallery[autoCount].subImages[0].length) {
      activeImage.attr('src', carsGallery[autoCount].mainImages).stop(true, true).hide().fadeIn();
      subImageSliderPage = 0;
    } else {
      activeImage.attr('src', carsGallery[0].subImages[0][subImageSliderPage]).stop(true, true).hide().fadeIn();
      subImageSliderPage++;
    }
  });

  $('#leftArrow').click(function() {


  });
});


function startSlider() {
  activeImage.attr('src', carsGallery[0].mainImages).stop(true, true).hide().fadeIn();
  timerId = setInterval(function() {

    if (stopSlider != true) {
      if (autoCount >= carsGallery.length - 1) {
        autoCount = 0;
      }
      activeImage.attr('src', carsGallery[autoCount].mainImages).stop(true, true).hide().fadeIn();
      autoCount++;
    }

  }, options.Image.SecPerSlide);
}

function pauseSlider(state) {
  stopSlider = state;
}
#AutoSlider {
  min-height: 320px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

<div class="col-sm-12 story-for-sale sold-cars-box">
  <div class="col-sm-10 col-sm-offset-1 story-for-sale sold-cars-box">
    <div id="AutoSlider" onmouseover="pauseSlider(true);" onmouseout="pauseSlider(false);">
      <div hidden class="carImages">

        <div class="mainPhoto">
          <img src="https://cdn.motor1.com/images/mgl/7WjgW/s4/1974-lancia-stratos-hf-stradale-for-sale.jpg" />
        </div>
        <div class="interior">
          <img src="https://i.pinimg.com/originals/0e/91/97/0e9197574f9f55aec58af0fe5ff265bb.jpg" class="interior0" />
        </div>

        <div class="mainPhoto">
          <img src="http://dmi3w0goirzgw.cloudfront.net/gallery-images/840x560/274000/600/274681.jpg" />
        </div>
        <div class="interior">
          <img src="https://i.pinimg.com/originals/35/39/bd/3539bdb4edefb3a862e30386b8519ea1.jpg" class="interior1" />
        </div>

        <div class="mainPhoto">
          <img src="https://cdn.motor1.com/images/mgl/7WjgW/s4/1974-lancia-stratos-hf-stradale-for-sale.jpg" />
        </div>
        <div class="interior">
          <img src="https://i.pinimg.com/originals/0e/91/97/0e9197574f9f55aec58af0fe5ff265bb.jpg" class="interior2" />
        </div>

        <div class="mainPhoto">
          <img src="http://dmi3w0goirzgw.cloudfront.net/gallery-images/840x560/274000/600/274681.jpg" />
        </div>
        <div class="interior">
          <img src="https://i.pinimg.com/originals/35/39/bd/3539bdb4edefb3a862e30386b8519ea1.jpg" class="interior3" />
        </div>

        <div class="mainPhoto">
          <img src="https://cdn.motor1.com/images/mgl/7WjgW/s4/1974-lancia-stratos-hf-stradale-for-sale.jpg" />
        </div>
        <div class="interior">
          <img src="https://i.pinimg.com/originals/0e/91/97/0e9197574f9f55aec58af0fe5ff265bb.jpg" class="interior4" />
        </div>

        <div class="mainPhoto">
          <img src="http://dmi3w0goirzgw.cloudfront.net/gallery-images/840x560/274000/600/274681.jpg" />
        </div>
        <div class="interior">
          <img src="https://i.pinimg.com/originals/35/39/bd/3539bdb4edefb3a862e30386b8519ea1.jpg" class="interior5" />
        </div>

        <div class="mainPhoto">
          <img src="https://cdn.motor1.com/images/mgl/7WjgW/s4/1974-lancia-stratos-hf-stradale-for-sale.jpg" />
        </div>
        <div class="interior">
          <img src="https://i.pinimg.com/originals/0e/91/97/0e9197574f9f55aec58af0fe5ff265bb.jpg" class="interior6" />
        </div>

        <div class="mainPhoto">
          <img src="http://dmi3w0goirzgw.cloudfront.net/gallery-images/840x560/274000/600/274681.jpg" />
        </div>
        <div class="interior">
          <img src="https://i.pinimg.com/originals/35/39/bd/3539bdb4edefb3a862e30386b8519ea1.jpg" class="interior7" />
        </div>

      </div>
    </div>
  </div>
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...