使用 JavaScript 禁用水平滚动
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7503048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Disable horizontal scroll with JavaScript
提问by Jay
Does anyone know if there is a way to disable the horizontal scrollbar using JavaScript?
有谁知道是否有办法使用 JavaScript 禁用水平滚动条?
I don't want to use overflow-x: hidden;
.
我不想使用overflow-x: hidden;
.
回答by Chris Baker
Without using the perfectly workable overflow-x
CSS property, you could resize the content to not require a scroll bar, through javascript or through HTML/CSS design.
在不使用完美可行的overflow-x
CSS 属性的情况下,您可以通过 javascript 或通过 HTML/CSS 设计调整内容大小以不需要滚动条。
You could also do this:
你也可以这样做:
window.onscroll = function () {
window.scrollTo(0,0);
}
... which will detect any scrolling and automatically return the scroll to the top/left. It bears mentioning that doing something like this is sure to frustrate your users.
...这将检测任何滚动并自动将滚动返回到顶部/左侧。值得一提的是,做这样的事情肯定会让你的用户感到沮丧。
You're best served by creating an environment where unwanted UI elements are not present at all (through the CSS, through design). The approach mentioned above shows unnecessary UI elements (scroll bars) and then causes them to not work in a way that the user expects (scroll the page). You've "broken a contract" with the user - how can they trust that the rest of your web site or application will do expected things when the user makes a familiar action?
创建一个完全不存在不需要的 UI 元素的环境(通过 CSS,通过设计),可以为您提供最好的服务。上面提到的方法显示了不必要的 UI 元素(滚动条),然后导致它们无法以用户期望的方式工作(滚动页面)。您已经与用户“破坏了合同”——当用户做出熟悉的操作时,他们怎么能相信您的网站或应用程序的其余部分会做预期的事情?
回答by Lekensteyn
A way to prevent elements from scrolling down in jQuery:
一种防止元素在 jQuery 中向下滚动的方法:
$(element).scroll(function () {
this.scrollTop = 0;
this.scrollLeft = 0;
});
Well, this does not actually prevent the scrolling, but it "scrolls back" to the top-left corner of an element, similar to Chris' solution which was created for the window instead of single elements. Remove the scrollTop
or scrollLeft
lines to suit your needs.
嗯,这实际上并不会阻止滚动,但它会“回滚”到元素的左上角,类似于 Chris 为窗口而不是单个元素创建的解决方案。删除scrollTop
或scrollLeft
行以满足您的需要。
回答by pimvdb
A dirty trick would be overlapping the scrollbars: http://jsfiddle.net/dJqgf/.
一个肮脏的技巧是重叠滚动条:http: //jsfiddle.net/dJqgf/。
var overlap = $('<div id=b>');
$("#a").wrap($('<div>'));
$("#a").parent().append(overlap);
with:
和:
#a {
width: 100px;
height: 200px;
overflow-x: scroll;
}
#b {
position: relative;
left: 0;
bottom: 20px;
width: 100%;
height: 20px;
background-color: white;
}