我试图禁用父母的html/身体滚动条,而我正在使用一个灯箱。这里的主要词是disable。我不想用溢出来隐藏它。
这样做的原因是overflow: hidden会使站点跳转并占用原来滚动的区域。
我想知道是否有可能禁用滚动条,同时仍然显示它。
我试图禁用父母的html/身体滚动条,而我正在使用一个灯箱。这里的主要词是disable。我不想用溢出来隐藏它。
这样做的原因是overflow: hidden会使站点跳转并占用原来滚动的区域。
我想知道是否有可能禁用滚动条,同时仍然显示它。
当前回答
我注意到YouTube网站就是这么做的。所以通过检查它一点,我已经能够确定他们正在使用@聚合物/铁覆盖-行为,幸运的是,它可以在web组件/聚合物之外使用:
import {
pushScrollLock,
removeScrollLock,
} from '@polymer/iron-overlay-behavior/iron-scroll-manager';
// lock scroll everywhere except scrollElement
pushScrollLock(scrollElement);
// restore scrolling
removeScrollLock(scrollElement);
允许滚动选定的元素 不会以任何方式干扰样式 是否在YouTube网站上进行了实战测试
这似乎是一个成熟的解决方案,当然也是我能找到的最好的解决方案。包装有点重,但我猜大部分都是分开的,当只进口铁卷轴管理器。
干杯
其他回答
你不能禁用滚动事件,但是你可以禁用导致滚动的相关操作,比如鼠标滚轮和touchmove:
$('body').on('mousewheel touchmove', function(e) {
e.preventDefault();
});
我也遇到过类似的问题:左侧菜单出现时,无法滚动。一旦高度设置为100vh,滚动条就会消失,内容会向右抽搐。
因此,如果你不介意保持滚动条启用(但设置窗口全高,这样它实际上不会滚动到任何地方),那么另一种可能性是设置一个小的底部边距,这将保持滚动条显示:
body {
height: 100vh;
overflow: hidden;
margin: 0 0 1px;
}
你可以用overflow: hidden隐藏正文的滚动条,同时设置一个边距,这样内容就不会跳转:
let marginRightPx = 0;
if(window.getComputedStyle) {
let bodyStyle = window.getComputedStyle(document.body);
if(bodyStyle) {
marginRightPx = parseInt(bodyStyle.marginRight, 10);
}
}
let scrollbarWidthPx = window.innerWidth - document.body.clientWidth;
Object.assign(document.body.style, {
overflow: 'hidden',
marginRight: `${marginRightPx + scrollbarWidthPx}px`
});
然后你可以在页面上添加一个禁用的滚动条来填补空白:
textarea { overflow-y:滚动; overflow-x:隐藏; 宽度:11 px; 大纲:没有; 调整:没有; 位置:固定; 上图:0; 右:0; 底部:0; 边界:0; } textarea > < textarea > < /
我在我自己的灯箱实现中就是这样做的。目前看来还不错。
如果覆盖层下的页面可以“固定”在顶部,当你打开覆盖层时,你可以设置
.disableScroll { position: fixed; overflow-y:scroll }
将这个类提供给可滚动的主体,您仍然应该看到正确的滚动条,但内容是不可滚动的。
用jquery来保持页面的位置
$('body').css('top', - ($(window).scrollTop()) + 'px').addClass('disableScroll');
当你关闭覆盖时,只需恢复这些属性
var top = $('body').position().top;
$('body').removeClass('disableScroll').css('top', 0).scrollTop(Math.abs(top));
我之所以建议采用这种方式,只是因为您不需要更改任何滚动事件
我喜欢坚持使用“overflow: hidden”方法,只需添加与滚动条宽度相等的右填充。
通过lostsource获取滚动条宽度函数。
function getScrollbarWidth() {
var outer = document.createElement("div");
outer.style.visibility = "hidden";
outer.style.width = "100px";
outer.style.msOverflowStyle = "scrollbar"; // needed for WinJS apps
document.body.appendChild(outer);
var widthNoScroll = outer.offsetWidth;
// force scrollbars
outer.style.overflow = "scroll";
// add innerdiv
var inner = document.createElement("div");
inner.style.width = "100%";
outer.appendChild(inner);
var widthWithScroll = inner.offsetWidth;
// remove divs
outer.parentNode.removeChild(outer);
return widthNoScroll - widthWithScroll;
}
当显示覆盖时,在html中添加"noscroll"类,并在body中添加padding-right:
$(html).addClass("noscroll");
$(body).css("paddingRight", getScrollbarWidth() + "px");
当隐藏时,删除类和填充:
$(html).removeClass("noscroll");
$(body).css("paddingRight", 0);
noscroll样式是这样的:
.noscroll { overflow: hidden; }
注意,如果你有任何带有position:fixed的元素,你也需要为这些元素添加填充。