关于通过 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/