我正在使用scrollTo jQuery插件,想知道是否有可能通过Javascript暂时禁用窗口元素上的滚动?我想禁用滚动的原因是,当你滚动而scrollTo是动画,它变得非常难看;)
当然,我可以做$("body").css("overflow", "hidden");然后当动画停止时把它放回自动,但如果滚动条仍然可见但不活跃会更好。
我正在使用scrollTo jQuery插件,想知道是否有可能通过Javascript暂时禁用窗口元素上的滚动?我想禁用滚动的原因是,当你滚动而scrollTo是动画,它变得非常难看;)
当然,我可以做$("body").css("overflow", "hidden");然后当动画停止时把它放回自动,但如果滚动条仍然可见但不活跃会更好。
当前回答
这里有一个非常基本的方法:
window.onscroll = function () { window.scrollTo(0, 0); };
在IE6中有点不稳定。
其他回答
我发现改变身体的风格是没有必要的。
我们唯一需要做的就是防止整个文档(html元素)出现y滚动。
我们可以用Javascript来创建和销毁样式表。我是这样做的:
https://jsfiddle.net/3os72ryk/
var scroll_style_element;
function disable_scrolling(){
// Create a style sheet we will only use to disable scrolling :
scroll_style_element = document.createElement('style');
document.head.appendChild(scroll_style_element);
const scroll_style_sheet = scroll_style_element.sheet;
scroll_style_sheet.insertRule('html{height:100%;overflow-y:hidden;}', scroll_style_sheet.cssRules.length);
}
function enable_scrolling(){
if( scroll_style_element ) document.head.removeChild(scroll_style_element);
}
非常有兴趣知道是否有人发现这种方法有问题,所以如果你发现了,请在下面评论。
this.style.overflowX = 'hidden'; 您可以在函数中使用此代码行,并在被单击的特定元素上工作。
我也有同样的问题,下面是我处理它的方法。
/* file.js */
var body = document.getElementsByTagName('body')[0];
//if window dont scroll
body.classList.add("no-scroll");
//if window scroll
body.classList.remove("no-scroll");
/* file.css */
.no-scroll{
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
希望这对你有所帮助。
我一直在寻找这个问题的解决方案,但对上面的任何解决方案都不满意(在写这个答案时),所以我想出了这个解决方案。
CSS
.scrollDisabled {
position: fixed;
margin-top: 0;// override by JS to use acc to curr $(window).scrollTop()
width: 100%;
}
JS
var y_offsetWhenScrollDisabled=0;
function disableScrollOnBody(){
y_offsetWhenScrollDisabled= $(window).scrollTop();
$('body').addClass('scrollDisabled').css('margin-top', -y_offsetWhenScrollDisabled);
}
function enableScrollOnBody(){
$('body').removeClass('scrollDisabled').css('margin-top', 0);
$(window).scrollTop(y_offsetWhenScrollDisabled);
}
var winX = null;
var winY = null;
window.addEventListener('scroll', function () {
if (winX !== null && winY !== null) {
window.scrollTo(winX, winY);
}
});
function disableWindowScroll() {
winX = window.scrollX;
winY = window.scrollY;
}
function enableWindowScroll() {
winX = null;
winY = null;
}