Нажатие на div не приводит к прокрутке элементов, как это должно быть с использованием jQuery - PullRequest
1 голос
/ 23 сентября 2019

У меня есть следующий код с обработчиками кликов:

$(document).ready(function() {
  $('.black-btn').click(function() {
    $('.popup-cats-wrapper').animate({
      scrollTop: $(".black-anchor").offset().top - 100
    }, 400)
  });
  $('.red-btn').click(function() {
    $('.popup-cats-wrapper').animate({
      scrollTop: $(".red-anchor").offset().top - 100
    }, 400)
  });
  $('.green-btn').click(function() {
    $('.popup-cats-wrapper').animate({
      scrollTop: $(".green-anchor").offset().top - 100
    }, 400)
  });
  $('.blue-btn').click(function() {
    $('.popup-cats-wrapper').animate({
      scrollTop: $(".blue-anchor").offset().top - 100
    }, 400)
  });


});
body {
  font-size: 12px;
  font-family: "sans";
}

.hero-categories-wrap {
  overflow: hidden;
  height: 200px;
}

.popup-cats-wrapper {
  height: 200px;
  width: 300px;
  background: #aaa;
  display: inline-block;
  padding-top: 20px;
  padding-left: 20px;
  padding-right: 20px;
  padding-bottom: 0px;
  overflow-x: auto;
}

.categories-sidebar {
  width: 120px;
  background: #ececef;
  height: 200px;
  padding-top: 20px;
  float: left;
}

.popup-menu-row {
  padding: 5px 8px;
  color: #212121;
  font-weight: 600;
  cursor: pointer;
  border-radius: 25px;
  margin-bottom: 5px;
}

.color-block {
  margin-bottom: 10px;
  margin-top: 25px;
}

.cat-title {
  font-weight: 600;
  font-size: 12px;
  color: #000;
  margin-bottom: 15px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="hero-categories-wrap">

  <div class="categories-sidebar">
    <div class="popup-menu-row black-btn">BLACK</div>
    <div class="popup-menu-row red-btn">RED</div>
    <div class="popup-menu-row green-btn">GREEN</div>
    <div class="popup-menu-row blue-btn">BLUE</div>
  </div>
  <div class="popup-cats-wrapper">

    <div class="color-block">
      <div class="cat-title black-anchor">BLACK COLOR</div>
      <div class="cat-description">Black is the darkest color, the result of the absence or complete absorption of visible light. It is an achromatic color, a color without hue, like white and gray.</div>
    </div>

    <div class="color-block">
      <div class="cat-title red-anchor">RED COLOR</div>
      <div class="cat-description">Red is the color at the end of the visible spectrum of light, next to orange and opposite violet. It has a dominant wavelength of approximately 625–740 nanometres. It is a primary color in the RGB color model and the CMYK color model, and is the
        complementary color of cyan.</div>
    </div>


    <div class="color-block">
      <div class="cat-title green-anchor">GREEN COLOR</div>
      <div class="cat-description">Green is the color between blue and yellow on the visible spectrum. It is evoked by light which has a dominant wavelength of roughly 495–570 nm. </div>
    </div>

    <div class="color-block">
      <div class="cat-title blue-anchor">BLUE COLOR</div>
      <div class="cat-description">Blue is one of the three primary colours of pigments in painting and traditional colour theory, as well as in the RGB colour model. It lies between violet and green on the spectrum of visible light. The eye perceives blue when observing light with
        a dominant wavelength between approximately 450 and 495 nanometres. Most blues contain a slight mixture of other colours; azure contains some green, while ultramarine contains some violet.</div>
    </div>

  </div>
</div>

К сожалению, когда я нажимаю на любую из кнопок (div) слева, якорные ссылки на правой стороне ведут себя очень странно.С другой стороны, если вы попытаетесь нажать один и тот же btn (например, green-btn) более одного раза, он прокручивает содержимое вверх и вниз!

Что я делаю неправильно?

1 Ответ

1 голос
/ 23 сентября 2019

Ваша проблема в том, что .offset().top дает вам текущее смещение этого элемента к его родителю, которое вы затем используете, чтобы установить для родителей scrollTop.Что вам нужно сделать, это добавить элементы .offset().top к текущему scrollTop родительского элемента.

$(document).ready(function() {
  
  var $wrapper = $('.popup-cats-wrapper');

  $('.black-btn').click(function() {
    $wrapper.animate({
      scrollTop: $wrapper.scrollTop() + $(".black-anchor").offset().top - 10
    }, 400)
  });
  $('.red-btn').click(function() {
    $wrapper.animate({
      scrollTop: $wrapper.scrollTop() + $(".red-anchor").offset().top - 10
    }, 400)
  });
  $('.green-btn').click(function() {
    $wrapper.animate({
      scrollTop: $wrapper.scrollTop() + $(".green-anchor").offset().top - 10
    }, 400)
  });
  $('.blue-btn').click(function() {
    $wrapper.animate({
      scrollTop: $wrapper.scrollTop() + $(".blue-anchor").offset().top - 10
    }, 400)
  });


});
body {
  font-size: 12px;
  font-family: "sans";
}

.hero-categories-wrap {
  overflow: hidden;
  height: 200px;
}

.popup-cats-wrapper {
  height: 200px;
  width: 300px;
  background: #aaa;
  display: inline-block;
  padding-top: 20px;
  padding-left: 20px;
  padding-right: 20px;
  padding-bottom: 0px;
  overflow-x: auto;
}

.categories-sidebar {
  width: 120px;
  background: #ececef;
  height: 200px;
  padding-top: 20px;
  float: left;
}

.popup-menu-row {
  padding: 5px 8px;
  color: #212121;
  font-weight: 600;
  cursor: pointer;
  border-radius: 25px;
  margin-bottom: 5px;
}

.color-block {
  margin-bottom: 10px;
  margin-top: 25px;
}

.cat-title {
  font-weight: 600;
  font-size: 12px;
  color: #000;
  margin-bottom: 15px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="hero-categories-wrap">

  <div class="categories-sidebar">
    <div class="popup-menu-row black-btn">BLACK</div>
    <div class="popup-menu-row red-btn">RED</div>
    <div class="popup-menu-row green-btn">GREEN</div>
    <div class="popup-menu-row blue-btn">BLUE</div>
  </div>
  <div class="popup-cats-wrapper">

    <div class="color-block">
      <div class="cat-title black-anchor">BLACK COLOR</div>
      <div class="cat-description">Black is the darkest color, the result of the absence or complete absorption of visible light. It is an achromatic color, a color without hue, like white and gray.</div>
    </div>

    <div class="color-block">
      <div class="cat-title red-anchor">RED COLOR</div>
      <div class="cat-description">Red is the color at the end of the visible spectrum of light, next to orange and opposite violet. It has a dominant wavelength of approximately 625–740 nanometres. It is a primary color in the RGB color model and the CMYK color model, and is the
        complementary color of cyan.</div>
    </div>


    <div class="color-block">
      <div class="cat-title green-anchor">GREEN COLOR</div>
      <div class="cat-description">Green is the color between blue and yellow on the visible spectrum. It is evoked by light which has a dominant wavelength of roughly 495–570 nm. </div>
    </div>

    <div class="color-block">
      <div class="cat-title blue-anchor">BLUE COLOR</div>
      <div class="cat-description">Blue is one of the three primary colours of pigments in painting and traditional colour theory, as well as in the RGB colour model. It lies between violet and green on the spectrum of visible light. The eye perceives blue when observing light with
        a dominant wavelength between approximately 450 and 495 nanometres. Most blues contain a slight mixture of other colours; azure contains some green, while ultramarine contains some violet.</div>
    </div>

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