我有<DIV>
和<TEXTAREA>
,问题是元素(将接收同步)的滚动次数超过预期,而不是百分比。
到目前为止,我设法做到了这一点:
function syncScroll(from, to)
{
var sf = from.scrollHeight - from.clientHeight,
st = to.scrollHeight - to.clientHeight;
if (sf < 1) {
return;
}
var p = (sf / 100) * from.scrollTop;
to.scrollTop = (st / 100) * p;
}
window.onload = function() {
var currentScrollEvt, timer;
var editor = document.querySelector(".editor");
var preview = document.querySelector(".preview");
preview.innerHTML = editor.value;
editor.onscroll = function() {
if (currentScrollEvt === "preview") {
return;
}
clearTimeout(timer);
currentScrollEvt = "editor";
syncScroll(editor, preview);
timer = setTimeout(function() {
currentScrollEvt = null;
}, 200);
};
preview.onscroll = function() {
if (currentScrollEvt === "editor") {
return;
}
clearTimeout(timer);
currentScrollEvt = "preview";
syncScroll(preview, editor);
timer = setTimeout(function() {
currentScrollEvt = null;
}, 200);
};
};
html, body {
padding: 0;
margin: 0;
height: 100%;
}
* {
box-sizing: content-box;
}
body {
display: flex;
}
.editor, .preview {
flex: 1;
}
.preview {
background-color: #f00;
overflow: auto;
float: right;
}
<textarea class="editor">
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
a <br>
</textarea>
<div class="preview"></div>