在纯 javascript 中,您可以简单地将处理程序附加到用于鼠标移动的分区和用于滚动事件的窗口:
if (!window.addEventListener) { // for compatibility with IE6-8
window.addEventListener = function (type, listener, useCapture) {
attachEvent('on' + type, function () {
listener(event)
});
}
}
var display, divs, divslen;
window.addEventListener('load', function () {
display = document.getElementById('display_div');
divs = document.getElementById('leftpane').getElementsByTagName('div');
divslen = divs.length; // collection length
for (var i = 0; i < divslen; i++) {
divs[i].onmouseover = function () {
display.innerHTML = this.innerHTML;
};
}
}, false);
window.addEventListener('scroll', update_display_div, false);
window.addEventListener('resize', update_display_div, false);
function update_display_div() {
var updated = false;
for (var i = 0; i < divslen; i++) {
var rect = divs[i].getBoundingClientRect();
if (!updated && rect.top > -20) {
display.innerHTML = divs[i].innerHTML; //show topmost div
updated = true;
}
}
}
jsfiddle
感谢 Michal Klouda 参考 getBoundingClientRect() 函数。