在 2 个 div 之间同步滚动 [英] synchronizing scrolling between 2 divs
问题描述
我看到这篇文章并试图复制它,但没有成功 -同步滚动
I saw this post and tried to copy it but it didn't work - Syncing scrolling
我有一个带有 2 个标签的 TabContainer,其中有 div、bmrDetailDataDiv 和 residentDetailDataDiv.
I have a TabContainer with 2 tabs that have divs, bmrDetailDataDiv and residentDetailDataDiv.
这是我的 javascript 代码 -
Here is my javscript code -
window.onload = function () {
var bmrDetailDiv = $("div[id$='_bmrDetailDataDiv']")[0];
var residentDetailDiv = $("div[id$='_residentDetailDataDiv']")[0];
if ((bmrDetailDiv) && (residentDetailDiv)) {
bmrDetailDiv.on('scroll', function () {
residentDetailDiv.scrollTop(bmrDetailDiv.scrollTop());
});
residentDetailDiv.on('scroll', function () {
bmrDetailDiv.scrollTop(residentDetailDiv.scrollTop());
});
}
我错过了什么吗?
编辑 -
试过这个并得到一个错误 -
Tried this and get an error -
$(document).ready(function () {
var bmrDetailDiv = $("div[id$='_bmrDetailDataDiv']");
var residentDetailDiv = $("div[id$='_residentDetailDataDiv']");
if (bmrDetailDiv.length && residentDetailDiv.length) {
bmrDetailDiv.on('scroll', function () {
residentDetailDiv.scrollTop($(this).scrollTop());
});
residentDetailDiv.on('scroll', function () {
bmrDetailDiv.scrollTop($(this).scrollTop());
});
}
});
编辑 #2 -
试过了,还是出现 JScript 错误.这一切都在我的 .js 文件中,该文件包含在页面顶部.-
Tried this and still getting JScript error. This is all within my .js file that get's included at the top of the page. -
jQuery.fn.exists = function () { return this.length > 0; }
$(function () {
var combined = $("div[id$='_bmrDetailDataDiv']").add($("div[id$='_residentDetailDataDiv']"));
if (combined.exists()) {
//Getting error on below line
combined.on("scroll", function () {
combined.scrollTop($(this).scrollTop());
});
}
});
推荐答案
始终检查控制台 - 这将导致错误,因为您试图在本机元素上使用 jQuery 方法(因为您通过 [0]代码>).如果您这样做纯粹是为了
if
条件,则没有必要 - 检查选择器找到的元素,您只需查询 length
属性即可.
Always check the console - that will cause errors because you are attempting to use jQuery methods on native elements (since you retrieved them via [0]
). If you were doing this purely for the sake of the if
condition, there's no need - to check the selectors found elements, you can just query the length
property.
$(function() {
var bmrDetailDiv = $("div[id$='_bmrDetailDataDiv']");
var residentDetailDiv = $("div[id$='_residentDetailDataDiv']");
if (bmrDetailDiv.length && residentDetailDiv.length) {
bmrDetailDiv.on('scroll', function () {
residentDetailDiv.scrollTop($(this).scrollTop());
});
residentDetailDiv.on('scroll', function () {
bmrDetailDiv.scrollTop($(this).scrollTop());
});
}
});
其他变化:
1) 文档就绪处理程序而不是 window.onload
1) Document ready handler instead of window.onload
2) 在事件回调中使用 $(this)
2) Use of $(this)
inside event callback
这篇关于在 2 个 div 之间同步滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!