当孩子位于顶部/底部边界时,将自动滚动div

时间:2018-10-19 10:40:42

标签: jquery

我的代码有效,但是当parent到达其父级的底部/顶部时,最好自动滚动titleact,这样它始终可见。

我用offsetpositionscrollTop尝试了各种方法,但都没有成功。

$('.btnup').click(function() {
  let i = $('.titleact').index('.title');
  if (i == 0) {
    return;
  }
  let targ = $('.title').eq(i - 1);
  $('.titleact').insertBefore(targ);
});

$('.btndown').click(function() {
  let i = $('.titleact').index('.title');
  let count = $('.title').length;
  if (i == count - 1) {
    return;
  }
  let targ = $('.title').eq(i + 1);
  $('.titleact').insertAfter(targ);
});
.parent {
  width: 250px;
  height: 120px;
  overflow-y: scroll;
  background: lightblue;
}

.title {
  cursor: pointer;
  padding: 0 9px;
  line-height: 23px;
  margin: 5px 0;
}

.titleact {
  background: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class='parent'>
  <div class='title titleact'>title 01</div>
  <div class='title'>title 02</div>
  <div class='title'>title 03</div>
  <div class='title'>title 04</div>
  <div class='title'>title 05</div>
  <div class='title'>title 06</div>
  <div class='title'>title 07</div>
  <div class='title'>title 08</div>
  <div class='title'>title 09</div>
  <div class='title'>title 10</div>
</div>
<br>
<button class='btnup'>UP</button>
<button class='btndown'>DOWN</button>

1 个答案:

答案 0 :(得分:0)

您需要在scrollTop当前位置向$(".parent")应用$(".titleact")动画功能

检查以下代码:

$(document).ready(function () {

    $('.btnup').click(function () {
        let i = $('.titleact').index('.title');
        if (i == 0) {
            return;
        }
        let targ = $('.title').eq(i - 1);
        $('.titleact').insertBefore(targ);
        scrollFunc();
    });

    $('.btndown').click(function () {
        let i = $('.titleact').index('.title');
        let count = $('.title').length;
        if (i == count - 1) {
            return;
        }
        let targ = $('.title').eq(i + 1);
        $('.titleact').insertAfter(targ);

        scrollFunc();
    });
});

function scrollFunc() {
    $(".parent").animate({ scrollTop: $(".parent").scrollTop() + $('.titleact').offset().top - 10 }, 'slow');
};
.parent {
    width: 250px;
    height: 120px;
    overflow-y: scroll;
    background: lightblue;
}

.title {
    cursor: pointer;
    padding: 0 9px;
    line-height: 23px;
    margin: 5px 0;
}

.titleact {
    background: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class='parent'>
    <div class='title titleact'>title 01</div>
    <div class='title'>title 02</div>
    <div class='title'>title 03</div>
    <div class='title'>title 04</div>
    <div class='title'>title 05</div>
    <div class='title'>title 06</div>
    <div class='title'>title 07</div>
    <div class='title'>title 08</div>
    <div class='title'>title 09</div>
    <div class='title'>title 10</div>
</div>
<br>
<button class='btnup'>UP</button>
<button class='btndown'>DOWN</button>