禁止水平滚动;但允许垂直滚动 [英] Disable horizontal scroll; but allow vertical scroll

查看:91
本文介绍了禁止水平滚动;但允许垂直滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在禁用网站上的横向滚动;

I'm trying to disable horizontal scroll on a website; but allowing vertical scrolling.

我有一个脚本,像滑块一样滑动左边的body,并显示更多的内容。但是,这会在右侧创建额外的空白空间。

I have a script which works like a slider by sliding the 'body' of the page left and revealing more contents. However this creates extra empty space on the right.

我需要禁用水平滚动,所以用户看不到这个空格。我尝试了以下脚本,但是它会禁用水平和垂直滚动:

I need to disable horizontal scrolling so users don't see this empty space. I tried the following script but it disables both horizontal and vertical scrolling:

window.onscroll = function () {
     window.scrollTo(0,0);
}

我尝试过 overflow-x:hidden 但是当身体的宽度是动态的而不是静态时,这不行。

I have tried overflow-x: hidden but that doesn't work when the body's width is dynamic and not static.

有没有办法修改上述脚本来禁用水平滚动并保持垂直滚动?

Is there a way to modify the above script to disable the horizontal scrolling and keep vertical scrolling?

推荐答案

你很接近了。您需要获得文档 - 窗口 - 并绑定滚动条:然后你可以检查 scrollLeft 是否更新为超过0 ,并将 scrollLeft 设置为 0

You were close to get it. You need to get the documentor window— and bind the scroll: then you can check if the scrollLeft is updated to more than 0 and set the scrollLeft to 0.

下一个代码工作正常:

$(function() {

    var $body = $(document);
    $body.bind('scroll', function() {
        // "Disable" the horizontal scroll.
        if ($body.scrollLeft() !== 0) {
            $body.scrollLeft(0);
        }
    });

}); 

如果要禁用元素的水平滚动如div,例如),您只需要将 $(document)替换为 $(#yourElementID)

If you want to disable horizontal scroll for an element (like div, for instance) you only need to replace $(document) by $("#yourElementID")

JSFiddle https://jsfiddle.net/tomloprod/zx1bvdf5/


注意:

上述脚本将阻止您水平滚动,此外,您还可以使用下一个CSS样式: overflow-x:hidden; 隐藏水平滚动。

The above script will prevent you scroll horizontally and, in addition, you can use the next CSS style: overflow-x:hidden; to hide the horizontal scroll.

如果没有水平滚动,就会像...

这篇关于禁止水平滚动;但允许垂直滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆