尝试以编程方式在溢出div中滚动scrollLeft,但$('el')。scrollLeft()始终返回零

时间:2018-11-27 18:59:39

标签: jquery

在下面-如何修改我的代码,以便在单击按钮时滚动位置发生变化,因此该按钮是第一个。我快到了,但是scrollLeft()总是为零

$('a').click( function() {
	const target = $(this).position().left;
  $('.msg').text(`Postition Left => ${target}`)
	$(".horz-scroll").scrollLeft(target)
})
.horz-scroll {
  overflow-y: scroll;
  -webkit-overflow-scrolling: touch;
  max-width: 100%;
  white-space: nowrap;
}

a {
  display: inline-block;
  padding: 2em;
  cursor: pointer;
  background: #000;
  color: #fff;
}

a:hover {
  background: lighten(#000,15%);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="horz-scroll">
    <a>Chassis</a>
    <a>Processor</a>
    <a>Memory</a>
    <a>Controllers</a>
    <a>Hard Drives</a>
    <a>Solid State Drives</a>
    <a>FlexibleLOM Network Controller</a>
    <a>HBAs</a>
    <a>iLO Advance</a>
    <a>Network Adapters</a>
    <a>Power Suppplies</a>
    <a>Rail Kits</a>
    <a>Accessories</a>
</div>

<br>
<div class="msg"></div>

1 个答案:

答案 0 :(得分:0)

使用箭头功能()=>{} $(this)不会引用目标。

可滚动容器的计算应为点击元素的currentScrollPos + .position().left

$('a').click( function() {
	const el = $(this).position().left;
  const currentScroll = $(".horz-scroll").scrollLeft();
  const target = el+currentScroll;
  $('.msg').text(`Postition Left => ${target}`)
	$(".horz-scroll").scrollLeft(target)
})
.horz-scroll {
  overflow-y: scroll;
  -webkit-overflow-scrolling: touch;
  max-width: 100%;
  white-space: nowrap;
}

a {
  display: inline-block;
  padding: 2em;
  cursor: pointer;
  background: #000;
  color: #fff;
}

a:hover {
  background: lighten(#000,15%);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="horz-scroll">
    <a>Chassis</a>
    <a>Processor</a>
    <a>Memory</a>
    <a>Controllers</a>
    <a>Hard Drives</a>
    <a>Solid State Drives</a>
    <a>FlexibleLOM Network Controller</a>
    <a>HBAs</a>
    <a>iLO Advance</a>
    <a>Network Adapters</a>
    <a>Power Suppplies</a>
    <a>Rail Kits</a>
    <a>Accessories</a>
</div>

<br>
<div class="msg"></div>