Javascript Jquery从用户在屏幕上的位置滚动一个像素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13815163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 14:50:48  来源:igfitidea点击:

Jquery Scroll One pixel from where ever the user is on screen

javascriptjqueryhtmlcssscroll

提问by Muhammed Bhikha

okay heres the scenario. I have a one page website with may sections using anchor links. Whe the user is on a secondary layout (page) and when they click on to go to a section on the main page again, for some reason the graphics dont load properly until a scroll happens. All I want to do is whenever the main layout is loaded, no matter which anchor it loads to, simply scroll the page up or down by 1 pixel.

好的继承人的场景。我有一个单页网站,其中可能有使用锚链接的部分。当用户在辅助布局(页面)上时,当他们再次单击以转到主页上的某个部分时,由于某种原因,图形在滚动发生之前无法正确加载。我想要做的就是每当加载主布局时,无论它加载到哪个锚点,只需将页面向上或向下滚动 1 个像素即可。

 $.scrollTo({ top: '+=100px', left: '+=0px' }, 800);

I tried the above, but this code simply takes the user 100 pixels from the top. I don't want that to happen, i.e. not from the top but from where ever the user is on screen.

我尝试了上面的方法,但是这段代码只是让用户从顶部开始 100 个像素。我不希望这种情况发生,即不是从顶部而是从用户在屏幕上的任何位置发生。

回答by Justin McDonald

use jquery scrollTop() to set the scroll position to the current scroll position + 1:

使用 jquery scrollTop() 将滚动位置设置为当前滚动位置 + 1:

$(window).scrollTop($(window).scrollTop()+1);

回答by Chris

A pure JavaScript solution without the jQuery overhead:

没有 jQuery 开销的纯 JavaScript 解决方案:

window.scrollY += 100;

With jQuery (and a fancy animation):

使用 jQuery(和精美的动画):

var cur = $(window).scrollTop();
$(window).animate({scrollTop: cur + 100});

回答by Bj?rn Stenfeldt

I have a similar problem. I want to scroll down 1 pixel and then 1 pixel up, so the user hopefully won't notice anything at all. I did this:

我有一个类似的问题。我想向下滚动 1 像素,然后向上滚动 1 像素,因此用户希望根本不会注意到任何东西。我这样做了:

window.scrollBy(0, 1); // 0 pixels horizontal and 1 pixel down
window.scrollBy(0, -1); // 0 pixels horizontal and 1 pixel up

UPDATE: But I might end up using JQuery instead. All I want is the scroll event to fire and I can do that with:

更新:但我最终可能会改用 JQuery。我想要的只是触发滚动事件,我可以这样做:

$(window).scroll();

回答by Laura Chesches

$("html, body").animate({scrollTop: ($(window).scrollTop() + 1)});