【问题标题】:pure javascript method to set x scroll position in a div with overflow-x纯javascript方法使用overflow-x在div中设置x滚动位置
【发布时间】:2014-12-03 06:23:06
【问题描述】:

如何使用纯 javascript 或 angularjs 设置具有水平/溢出-x 的 div 滚动的 x 位置?重要提示:我不是在寻找 jquery 解决方案 - 使用 angularjs,jquery 不会立即工作。

angularjs 中的

$anchorScroll() 滚​​动到垂直位置但不滚动到水平位置 afaik。 $window.scroll to 或 window.scrollTo(x,y) 不在 overflow-x div 内滚动。如果这里有人确定我尝试过的方法在某些修改下可以工作,我也想知道。

【问题讨论】:

  • @hindmost 我用 scrollLeft 尝试了一些东西,但没有用。也许我做错了。很想多听听。
  • 没有任何代码我只能猜测你的问题
  • @hindmost,我正在使用这个 document.getElementById ('target_div').scrollLeft=amount-x-move;稍后我会在我原来的问题中发布更多详细信息。
  • @hindmost:你是​​对的,scrollLeft 有效。谢谢。

标签: javascript angularjs scroll horizontal-scrolling


【解决方案1】:

你可以在 jQuery 上使用$(selector).scrollLeft(amountToMove);

document.getElementById(containerId).scrollLeft = amountToMove; 使用纯 JavaScript 或

angular.element(selector).scrollLeft(amountToMove); 使用 angularjs。

【讨论】:

  • 你被问到纯js,为什么要提供jquery?
  • 我只是在答案上写了三种方式,就这样。
【解决方案2】:

我偶然发现了这个我正在寻找解决这个问题的跨浏览器解决方案!
我发现元素上的 scrollBy 仅适用于 Firefox!
我知道这是一个老问题,但也许有人也像我一样寻找这个......
假设 div id 是滚动:

    function ScrollByLeft() {
          document.getElementById("scroll").scrollBy(10, 0);
    }
    function ScrollByRight() {
          document.getElementById("scroll").scrollBy(-10, 0);
    }

    function ScrollLeft() {
          document.getElementById("scroll").scrollLeft=10;
    }
    function ScrollRight() {
          document.getElementById("scroll").scrollLeft=-10;
    }
div#scroll {
	width: 180px;
	overflow-x: scroll;
}
<div id="scroll">
<p>
    Scroll.strange.wery.long.word.horizontally.for.10.pixels.left.and.right.also.but.only.on.Firefox.as.I.know</p>
</div>
<button onclick="ScrollByLeft()">ScrollBy Left!</button>
<button onclick="ScrollByRight()">ScrollBy Right!</button>
<br>
<button onclick="ScrollLeft()">ScrollLeft Left!</button>
<button onclick="ScrollRight()">ScrollLeft Right!</button>

限制:
据我所知,ScrollBy 仅适用于 Firefox...
其他浏览器只能这样滚动窗口!
不是其他元素...

【讨论】:

    猜你喜欢
    • 2020-07-11
    • 2017-12-21
    • 2014-03-25
    • 1970-01-01
    • 2011-03-28
    • 2021-11-14
    • 1970-01-01
    • 2013-10-29
    • 2022-01-05
    相关资源
    最近更新 更多