簡體   English   中英

對象在 React 的 IE11 中不支持屬性或方法“scrollBy”

[英]Object doesn't support property or method 'scrollBy' in IE11 in React

我正在使用以下代碼在 mouseDown 上滾動滾動元素,並在 mouseUp/mouseOut 上停止滾動。

scrubby(xDir) {
    let dub = setInterval(() => {
      document.getElementById("chart").scrollBy(8 * xDir, 0);
    }, 10);

    this.setState({ dub: dub });
  }

  scrubbyStop() {
    const { dub } = this.state;
    if (dub !== null) {
      clearInterval(dub);
    }
    this.setState({ dub: null });
  }

這適用於除 IE 11 以外的所有地方。在 IE 11 中,我收到以下錯誤:

TypeError: Object doesn't support property or method 'scrollBy'

當我 console.log 元素時,document.getElementById 以確保我選擇了元素。

我正在使用 babel-polyfil

我看到很多與 scrollTo 相關的問題,但不是 scrollBy。 有誰知道可能適用於 IE 的任何變通方法、polyfill 或替代方案。

Babel polyfill“將模擬完整的 ES2015+ 環境”。 然而,scrollBy不是 ECMAScript 規范的一部分,因此不會被 BabelscrollBy 您需要自己添加適當的 polyfill,例如平滑滾動行為scrollBy ,其中還包括scrollBy

我對這個問題晚了一年多,但是如果其他人面臨這個問題並且想要一個填寫scrollBy的解決方案,我正在使用 jQuery:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

...並將其添加到我頁面的 JavaScript 中:

if(!window.scrollBy){
  window.scrollBy = function(x, y){
    if(x) $('html, body').scrollLeft($(window).scrollLeft() + x);
    if(y) $('html, body').scrollTop($(window).scrollTop() + y);
  };
}

if(!Element.prototype.scrollBy){
  Element.prototype.scrollBy = function(x, y){
    if(x) $(this).scrollLeft($(this).scrollLeft() + x);
    if(y) $(this).scrollTop($(this).scrollTop() + y);
  };
}

它已在 IE 11 中測試和運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM