javascript - 防止 JavaScript 启动的滚动

标签 javascript jquery scroll

关于通过 JavaScript 阻止用户启动(即鼠标、触摸、键盘)滚动存在很多问题。在本例中,我正在 CMS 中创建一个组件,该组件需要阻止另一个 CMS 组件将自身滚动到 View 中。我无权访问其他 CMS 组件的代码(该代码也被严重混淆)。

我尝试使用以下代码禁用强制滚动的典型方法,但在以下代码运行一两秒后,其他 CMS 仍然滚动到 View 中:

  Element.prototype.scrollIntoView = function(alignWithTop){
    console.log("******** scrollIntoView: " + this.getAttribute("id"));
  };

  Element.prototype.scrollIntoViewIfNeeded = function(alignWithTop){
    console.log("******** scrollIntoViewIfNeeded: " + this.getAttribute("id"));
  };

  Element.prototype.scrollByLines = function(){
    console.log("******** scrollByLines: " + this.getAttribute("id"));
  };

  Element.prototype.scrollByPages = function(){
    console.log("******** scrollByPages: " + this.getAttribute("id"));
  };

  Element.prototype.focus = function(){
    console.log("******** focus: " + this.getAttribute("id"));
  };

  window.scroll = function(xpos,ypos){
    console.log("******** scroll: " + xpos+","+ypos);
  }

  window.scrollTo = function(xpos,ypos){
    console.log("******** scrollTo: " + xpos+","+ypos);
  }

  window.scrollBy = function(xpos,ypos){
    console.log("******** scrollBy: " + xpos+","+ypos);
  }

  jQuery.fn.scrollTop = function(){
    console.log("!!!!!!!! scrollTop");
  };

  jQuery.fn.animate = function(){
    console.log("!!!!!!!! animate");
  };

  jQuery.fn.click = function(){
    console.log("!!!!!!!! click");
  };

我可以设置window.onscroll来强制调用window.scrollTo(0,0)一段时间,但这似乎并不令人满意,因为它看起来很不稳定并阻止用户启动的滚动,这是我不想阻止的。

javascript(或 jQuery)是否有其他方法可以强制滚动我在上面的代码中丢失的内容?

最佳答案

所以这应该是显而易见的,但是 CMS 调用的函数是 HTMLElementObject.focus(),因此以下是我用来在页面加载和设置期间停止不必要的滚动的代码:

// Stop the page from jumping around for a little while
var oldFocus = Element.prototype.focus;
Element.prototype.focus = function(){};
setTimeout(
  function(){
    Element.prototype.focus = oldFocus;
  },5000);

关于javascript - 防止 JavaScript 启动的滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24139916/

相关文章:

javascript - 是否可以将系统输出放入 JavaScript 中的 var 中?

javascript - React Component 的状态用 .unshift() 渲染很奇怪,但是用 .push() 渲染正常

JavaScript:是否有失败图像请求的错误属性?

java - 如何在 Java Swing 中自动滚动到底部

javascript - 谷歌浏览器 document.body.scrollTop 总是返回 0

javascript - underscore _.each 和 forEach 有什么区别?

javascript - 在javascript中修改对象值的问题

javascript - 选择多个元素 height();

View 上所有按钮/链接点击或下拉更改的 jQuery 事件

javascript - CSS3 转换导致非常奇怪的 window.scrollY 行为