简体   繁体   English

将 scrollTop 值从 textarea 复制到 div

[英]Copy scrollTop value from textarea to div

I have a div and a textarea inside a parent div.我在父 div 中有一个 div 和一个 textarea。 I am trying to copy the scrollTop value of the textarea to the div so it moves in sync with the textarea scrolling.我正在尝试将 textarea 的 scrollTop 值复制到 div,以便它与 textarea 滚动同步移动。

The problem seems to be when i add text into the textarea and then press enter for a new line, the div scrollTop value doesn't seem to update but the textarea scrollTop value does.问题似乎是当我将文本添加到 textarea 中然后按 enter 换行时,div scrollTop 值似乎没有更新,但 textarea scrollTop 值更新了。

If i press enter again both values update but it seems the div scrollTop value is one step behind the textarea如果我再次按回车键,两个值都会更新,但似乎 div scrollTop 值比 textarea 落后一步

https://codesandbox.io/s/objective-feather-ngq8t https://codesandbox.io/s/objective-feather-ngq8t

handleScroll = (e) => {
   setTextareaScrollTop(e.target.scrollTop);
   e.target.previousElementSibling.scrollTop = e.target.scrollTop;
   setDivScrollTop(e.target.previousElementSibling.scrollTop);
};

在此处输入图像描述

I made some mod to your code, https://codesandbox.io/s/empty-voice-7w3ze我对你的代码做了一些修改, https://codesandbox.io/s/empty-voice-7w3ze

const useUpdate = () => {
  const [, dispatch] = useState(0);
  const ref = useRef(() => {
    dispatch((v) => v + 1);
  });

  return ref.current;
};

And when you need to repaint, just do当你需要重新粉刷时,就这样做

  handleScroll = (e) => {
    e.target.previousElementSibling.scrollTop = e.target.scrollTop;
    refresh();
  };

I didn't answer your question exactly according to what you want, but i noticed, there's no role the setState plays, so i removed both of them and replaced with a useUpdate .我没有完全按照你的要求回答你的问题,但我注意到, setState没有任何作用,所以我删除了它们并用useUpdate代替。 Let me know what you think on this approach.让我知道您对这种方法的看法。

If i remove both setState you had earlier, i do see the issue you described.如果我删除您之前的两个setState ,我确实会看到您描述的问题。

One simple workaround is to remove the setDivScrollTop from the handleScroll and add a new line \n after setting the red div's text.一种简单的解决方法是从handleScroll setDivScrollTop在设置红色 div 的文本后添加新行\n Note that this character acts like a caret and allows it to follow the other div.请注意,此字符的作用类似于插入符号,并允许它跟在另一个 div 之后。

handleScroll = (e) => {
    setTextareaScrollTop(e.target.scrollTop);
    e.target.previousElementSibling.scrollTop = e.target.scrollTop;
    // setDivScrollTop(e.target.scrollTop);
};

handleInput = (e) => {
    console.log(divScrollTop, textareaScrollTop)
    setText(e.target.value + "\n"); // add "\n"
};

As seen here, Codesandbox如这里所见, Codesandbox

Also I've added border style to the text area element and spellCheck={false} to make it possible to see they're equal.此外,我还向文本区域元素添加了边框样式,并添加了spellCheck={false}以便可以看出它们是相等的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM