jquery - 在 div 鼠标悬停时锁定主体滚动但保持位置

标签 jquery css ajax html scroll

我知道还有其他一些与此相关的问题(包括我刚才提出的一个问题),但我正在寻找一种方法来改进我发现唯一可行的解​​决方案。

我正在努力做到这一点,以便我可以使用鼠标滚轮滚动高度受限和 overflow: scroll; <div> ,还有一个将在 <div> 时继续工作包含在 <div> 中其内容来自 AJAX 调用。

在我的网络旅行中,我偶然发现了这个 fiddle :http://jsfiddle.net/mrtsherman/eXQf3/33/ .不幸的是,当从 AJAX 调用调用数据时,我无法让它工作 - 我不知道为什么会这样,所以如果有人知道这个问题,我将不胜感激一些建议!

虽然我有点跑题了,因为我的问题与我发现至少有效的唯一解决方案有关:添加 onmouseover 类。

DIV

<div onmouseover="$('html').addClass('noscroll');" 
     onmouseout="$('html').removeClass('noscroll');" 
     style="overflow:auto;max-height: 200px;">Data that is long</div>

CSS 类

html.noscroll
{
    position: fixed; 
    overflow-y: scroll;
    width: 100%;
}

我一直在使用这段代码,认为它可以完美运行,但我刚刚发现在较小的显示器上它会抛出一个更烦人的问题:跳回屏幕顶部!

似乎当position: fixed;被触发它确实禁用滚动条并保持可见(我想要)但它也会再次将滚动条一直移动到顶部,并且由于我的可滚动 div 位于页面的一半,因此无法使用。

最佳答案

对于这部分:

Unfortunately I cannot get this to work when the data is called from an AJAX call - I have no idea why this is happening, so if anyone is aware of this issue I'd appreciate some advice!

您只需更改少量代码:

$('#abs').on('mousewheel', function(e) {

After changes

bind 仅适用于存在的元素,不能附加到通过 ajax 获取的元素。来自 jQuery 网站:

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in .on() or .delegate().

Read more about .on() method


因此请尝试将您的代码更改为我向您展示的代码,并在更改后给我反馈。

关于jquery - 在 div 鼠标悬停时锁定主体滚动但保持位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16654875/

相关文章:

javascript - 如何正确编写这个 window.history.go(-historyCount)

html - 使用表格对时间表进行编码的替代方法

html - css如何在同一行显示3个按钮

java - Mule ESB - 如何在 Java 组件中处理来自网页的 JSON 请求

javascript - 未发送 XMLHttpRequest 发布数据

javascript - 通过javascript将图片上传到服务器

javascript - 模态窗口在右侧略微移动

javascript - 修复 iOS/iPad 2 中的溢出内容滚动

css - 根据封闭 DIV 的类设置链接样式

php - 使用PHP流/缓冲大型音频文件