gpt4 book ai didi

jQuery scrollLeft() 被浏览器自动滚动到最后位置劫持

转载 作者:太空宇宙 更新时间:2023-11-04 11:24:00 27 4
gpt4 key购买 nike

所以我试图让特定元素在页面加载时居中显示在屏幕上。该元素两侧各有一个元素,该元素占窗口宽度的 100%。

最终,会有更多的部分,我希望用户能够在所有部分之间自由滚动,尽管出于我正在做的网络应用程序的目的,我需要能够控制滚动也可以使用 javascript。

Here's a Fiddle to try it out.如您所见, fiddle 效果很好。现在,当我将它加载到我的页面上时,它会在正确的位置闪烁,然后转到浏览器认为它上次滚动的位置。如果你重新加载页面,那么它将是 0。如果你向右滚动一点,那么无论那个变量是什么,它都会接管并将元素滚动到那个位置而不是指定的位置。有时您会看到元素应该在的位置一闪而过,然后它会返回到浏览器认为您上次所在的位置。

您可以在这里看到一个实例:http://www.playafterdj.com/index2.php

简单的 HTML:

<div class="wrapper">
<section class="fill"></section>
<section class="init"></section>
<section class="fill"></section>
</div>

CSS:

* {
margin:0;
padding:0;
box-sizing:border-box;
}
html, body {
width:100%;
height:100%;
position:relative;
}
.wrapper {
width:100%;
height:100%;
position:relative;
white-space: nowrap;
}
section {
width: 100%;
max-width: 640px;
height: 100%;
background-color: #313138;
padding: 10px;
margin-right: 20px;
display: inline-block;
vertical-align: top;
}
section.fill {
width: 100%;
max-width:100%;
margin-right: 0;
background-color: transparent;
padding:0;
}

最后是 JS:

$(window).load(function(){
var winW = $(window).width();
var sectionW = $('.init').width();
var startPos = (winW/2)+(sectionW/2)+15;
$('body').scrollLeft(startPos);
});

因此,我使用 startPos 得到了正确的数字。在 fiddle 中,您可以通过滚动并查看 startPos 是否与正文的 scrollLeft() 匹配来对其进行测试。不幸的是,浏览器覆盖了它。我试过使用这几个答案但无济于事:

Prevent automatic browser scroll on refresh

Disable brower's auto scroll after a page refresh?

有什么建议吗?

最佳答案

看起来您正在尝试滚动 .wrapper div,但它未设置为可滚动。

.wrapper 上设置 overflow-x:scroll; 它将起作用。

.wrapper {
overflow-x:scroll;
}

http://jsfiddle.net/7ejL4koo/

或者,如果您要滚动的是body,而不是

$('.wrapper').scrollLeft(startPos);

$(document.body).scrollLeft(startPos);

http://jsfiddle.net/myydrL25/

这两种方法都有效。

关于jQuery scrollLeft() 被浏览器自动滚动到最后位置劫持,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32545691/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com