Лайтбокс не открывается из-за плавной прокрутки? - PullRequest
0 голосов
/ 20 марта 2019

Я пытаюсь реализовать эффект лайтбокса только для CSS для некоторых сертификатов на моем личном сайте. К сожалению, всякий раз, когда я щелкаю изображение, которое я хотел бы развернуть, оно либо прокручивается вверх страницы, либо просто немного вниз - вместо ориентации на полноразмерное изображение (я полагаю, это связано с запутанной логикой плавной прокрутки хешмарк в цели изображения с хешмарком в цели страницы). Я могу получить доступ к расширенному изображению только вручную, набрав адрес в браузере. Любые предложения ??

Вот ссылка на сайт.

enter image description here

enter image description here

    <div class="background-certs" id="certificates">  
  <div class="title-box">
    <h3 class="h3-web">{ certificates }</h3>
    <h4 class="h4-web">I enjoy learning</h4>
  </div>    

  <div class="cert-container">
    <a href="#cert-item-1" class="button-new">
      <div class="box1 grid-sub">
          <%= image_tag "firehose.jpg", class: "full-width-cert" %>
      </div>
      </a>
    <h4 class="h4-subtitle">software engineering bootcamp</h4>
    <p class="cert-subtitle">Dec. 2017 - Oct. 2018</p> 
  </div>

  <div class="cert-container">
    <a href="#cert-item-2" class="button-new">
      <div class="box1 grid-sub">
        <%= image_tag "udemy-js.jpg", class: "full-width-cert" %>
      </div>
    </a>  
    <h4 class="h4-subtitle">JavaScript: the weird parts</h4>
    <p class="cert-subtitle">Nov. 2018</p> 
  </div>

    <br class="clear" />

    <div class="cert-container">
      <a href="#cert-item-3" class="button-new">
        <div class="box1 grid-sub">
          <%= image_tag "udemy-algos.jpg", class: "full-width-cert" %>
        </div>
      </a> 
      <h4 class="h4-subtitle">algorithms + data structures</h4>
      <p class="cert-subtitle">Dec. 2018</p> 
    </div>

    <div class="cert-container">
      <a href="#cert-item-4" class="button-new">
        <div class="box1 grid-sub">
          <%= image_tag "udemy-shopify.jpg", class: "full-width-cert" %>
        </div>
      </a>
      <h4 class="h4-subtitle">shopify themes from scratch</h4>
      <p class="cert-subtitle">Feb. 2019</p> 
    </div>


    <div class="certificate-lightboxes">

      <div class="cert-lightbox" id="cert-item-1">
        <div class="cert-lightbox__content">
          <a href="#certificates" class="close"></a>
          <%= image_tag "firehose.jpg", class: "full-width-cert" %>
        </div>
      </div>

      <div class="cert-lightbox" id="cert-item-2">
        <div class="cert-lightbox__content">
          <a href="#certificates" class="close"></a>
          <%= image_tag "udemy-js.jpg", class: "full-width-cert" %>
        </div>
      </div>

      <div class="cert-lightbox" id="cert-item-3">
        <div class="cert-lightbox__content">
        <a href="#certificates" class="close"></a>
          <%= image_tag "udemy-algos.jpg", class: "full-width-cert" %>
        </div>
      </div>

      <div class="cert-lightbox" id="cert-item-4">
        <div class="cert-lightbox__content">
          <a href="#certificates" class="close"></a>
          <%= image_tag "udemy-shopify.jpg", class: "full-width-cert" %>
        </div>
      </div>

    </div>


    <div class="bottom-line"></div>
  </div> 
/** LIGHTBOX MARKUP **/

.cert-lightbox {
  display: flex;
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background: black;
  align-items: center;
  justify-content: center;
  transform: scale(0, 0);
  transition: transform ease-in-out 100ms;
}

.cert-lightbox:target {
  transform: scale(1, 1) !important;
  display: flex;
  z-index: 900;
}

.cert-lightbox__content {
  width: 65%;
  position: relative;
}

.close {
  position: absolute;
  width: 2em;
  height: 2em;
  background: red;
  top: -1em;
  right: -1em;
  border-radius: 50%;
  text-decoration: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close::after {
  content: "X";
  color: white;
  font-weight: 700;
}

плавная прокрутка в application.html.erb

<script type="text/javascript">
var $root = $('html, body');

$('a[href^="#"]').click(function () {
$root.animate({
    scrollTop: $( $.attr(this, 'href') ).offset().top
}, 400);

return false;
  });
  </script>

плавная прокрутка в scroll.js

 function scrollToHash(event) {
// On-page links
if (
  location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') 
  && 
  location.hostname == this.hostname
) {
  // Figure out element to scroll to
  var target = $(this.hash);
  target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
  // Does a scroll target exist?
  if (target.length) {
    // Only prevent default if animation is actually gonna happen
    event.preventDefault();
    $('html, body').animate({
      scrollTop: target.offset().top
    }, 1000, function() {
      // Callback after animation
      // Must change focus!
      var $target = $(target);
      $target.focus();
      if ($target.is(":focus")) { // Checking if the target was focused
        return false;
      } else {
        $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
        $target.focus(); // Set focus again
      };
    });
  }
}
};

  // Select all links with hashes
 $('a[href*="#"]')
  // Remove links that don't actually link to anything
   .not('[href="#"]')
  .not('[href="#0"]')
  .click(scrollToHash);

1 Ответ

1 голос
/ 21 марта 2019

Избегание присоединения слушателей с плавной прокруткой к ссылкам с атрибутом

В качестве небольшого улучшения по сравнению с добавлением нескольких вызовов .not, таких как .not('[href="#cert-item-1"]'), к вашей инициализации с плавной прокруткой, вы можете добавить собственный атрибут HTML data-no-smooth-scroll к каждой из ссылок лайтбокса ( о data- атрибутах ):

<div class="cert-container">
  <a href="#cert-item-1" data-no-smooth-scroll class="button-new"> <!-- added on this line -->
    <div class="box1 grid-sub">
      <%= image_tag "firehose.jpg", class: "full-width-cert" %>
    </div>
  </a>
  <h4 class="h4-subtitle">software engineering bootcamp</h4>
  <p class="cert-subtitle">Dec. 2017 - Oct. 2018</p> 
</div>

<!-- also add the attribute within the `a` for #cert-item-2, etc. -->

Тогда в JavaScript требуется только один .not:

// Select all links with hashes
$('a[href*="#"]')
  // Remove links that don't actually link to anything
  .not('[href="#"]')
  .not('[href="#0"]')
  .not('[data-no-smooth-scroll]') // this line was added
  .click(scrollToHash);

Селектор [data-no-smooth-scroll] является Селектором атрибутов .

Удаление слушателей с плавной прокруткой при настройке лайтбокса

В качестве альтернативы вы можете изменить код инициализации лайтбокса на вызов .off('click') (при условии, что он использует jQuery - вы не показывали этот код). Это удалит все существующие прослушиватели событий click из выбранных ссылок перед подключением новых прослушивателей событий click, которые открывают лайтбокс.

В некоторых случаях это будет чище, но при этом будет введено требование инициализации лайтбоксов после плавной прокрутки. Кроме того, если вы когда-нибудь добавите другой глобальный обработчик кликов, такой как Google Analytics, он также удалит этот обработчик. Поэтому я волнуюсь, что это решение будет трудно продолжать работать, так как код будет изменен в будущем.

...