2024-10-08 10:00:07

禁用水平滚动

好吧,出于某种原因,我的网页从左向右滚动,显示了很多丑陋的空间。

我已经搜索了结果,但他们只是使滚动条隐藏

这就是我现在想要的,我想在物理上禁用水平滚动功能。我不希望用户能够在我的页面上从左到右只是上下滚动!

我尝试过:overflow-x:隐藏在css上我的html标签,但它只是使滚动条隐藏,并没有禁用滚动。

请帮帮我!

这是一个页面链接:http://www.green-panda.com/usd309bands/(坏链接)

这可能会让你更好地理解我在说什么:

这是加载第一页的时候:

这是在我向右滚动之后:


当前回答

javascript中有一种方法可以帮助您检测哪个html元素导致水平溢出->滚动条出现

这里有一个关于CSS技巧的文章链接

var docWidth = document.documentElement.offsetWidth;
[].forEach.call(
  document.querySelectorAll('*'),
  function(el) {
    if (el.offsetWidth > docWidth) {
      console.log(el);
    }
  }
);

它可能返回如下内容:

<div class="class-of-the-div-with-extra-width">...</div>

然后你只需从div中删除额外的宽度或将其设置为max-width:100%

希望这能有所帮助!

它为我解决了这个问题。

其他回答

.name 
  { 
      max-width: 100%; 
       overflow-x: hidden; 
   }

你可以应用上面的风格,也可以用javaScript创建函数来解决这个问题

您可以使用JavaScript重写主体滚动事件,并将水平滚动重置为0。

function bindEvent(e, eventName, callback) {
    if(e.addEventListener) // new browsers
        e.addEventListener(eventName, callback, false);
    else if(e.attachEvent) // IE
        e.attachEvent('on'+ eventName, callback);
};

bindEvent(document.body, 'scroll', function(e) {
    document.body.scrollLeft = 0;
});

我不建议这样做,因为它限制了小屏幕用户的功能。

试着把它添加到你的CSS中

html, body {
    max-width: 100%;
    overflow-x: hidden;
}

如果您想禁用整个屏幕宽度的水平滚动,请使用此代码。

元素{ max-width: 100大众; overflow-x:隐藏; }

这比“100%”工作得更好,因为它忽略了父宽度,而是使用视口。

Koala_dev的答案是有效的,但如果你想知道为什么它是有效的:

.
q.html, body {              <--applying this css block to everything in the
                             html code.

q.max-width: 100%;          <--all items created must not exceed 100% of the 
                             users screen size. (no items can be off the page 
                             requiring scroll)

q.overflow-x: hidden;       <--anything that occurs off the X axis of the 
                             page is hidden, so that you wont see it going 
                             off the page.     

.