Javascript 执行jquery事件后如何保持页面滚动位置?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10836428/
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
How to maintain page scroll position after a jquery event is carried out?
提问by marky
I have searched high and low for an answer and have found similar examples of the problem but the answers do not apply to my scenario. The reality is I am new to this and therefore I don't have the skills to adapt the answers I have found to my problem.
我搜索了高低的答案,并找到了类似的问题示例,但这些答案不适用于我的场景。现实是我对此很陌生,因此我没有能力将我找到的答案调整到我的问题中。
The problem:
问题:
I have a Div in which when a thumbnail is clicked the Div image replaces with another image via a JavaScript/jQuery script (I am not sure exactly maybe someone could clarify). This works fine however the problem is the page scrolls back to the top and the user then has to scroll back down to see the image after it has replaced itself.
我有一个 Div,当单击缩略图时,Div 图像通过 JavaScript/jQuery 脚本替换为另一个图像(我不确定是否有人可以澄清)。这工作正常,但问题是页面滚动回顶部,然后用户必须向下滚动才能看到替换后的图像。
I have looked online and have found that a return false: in the JavaScript may help however I have looked and return false is already present.
我在网上查看并发现 return false: 在 JavaScript 中可能会有所帮助,但是我已经查看并返回 false 已经存在。
The other option I have looked at using is a JavaScript cookie based solution in which a cookie is sent, and the browser scroll position is maintain by reading the cookie however I cant seem to get that solution to work, I think the issue may be caused because I am hosting locally but I may be wrong...
我使用的另一个选项是基于 JavaScript cookie 的解决方案,其中发送 cookie,浏览器滚动位置通过读取 cookie 来维护,但是我似乎无法使该解决方案起作用,我认为问题可能是由因为我在本地托管,但我可能错了...
The third is using a PHP script but I have not found a definitive answer on this method and it also means I am going to have to learn about PHP (something I'm sure I will have to learn in time anyway).
第三个是使用 PHP 脚本,但我还没有找到关于这种方法的明确答案,这也意味着我将不得不学习 PHP(我相信无论如何我都必须及时学习)。
Here is the JavaScript:
这是 JavaScript:
<script type="text/javascript">
$(document).ready(function() {
$('.galleryicon').live("click", function() {
$('#mainImage').hide();
$('#cakebox').css('background-image', "url('ajax-loader.gif')");
var i = $('<img />').attr('src',this.href).load(function() {
$('#mainImage').attr('src', i.attr('src'));
$('#cakebox').css('background-image', 'none');
$('#mainImage').fadeIn();
});
return false;
});
});
</script>
Here is the html:
这是html:
<div class="cakecont">
<div id="cakebox">
<img src="../images/cakes/babycake1.png" alt="Main Image" id="mainImage"/>
<div class="pageinfo2">
<h3>Cake Type 1</h3>
<h6>£2.00</h6>
</div>
<div class="infobox">
<h6> Description </h6>
</div>
<div class="gallerybox">
<a href="../images/cakes/babycaketop.png" class="galleryicon">
<img src="../images/thumbs/babycaketopsml.png" alt="Thumbnail 2"/></a>
<a href="../images/cakes/babycake1.png" class="galleryicon">
<img src="../images/thumbs/babycakesml.png" alt="Image 1"/></a>
</div>
</div>
</div>
And here is a link to the working demo http://micahcarrick.com/code/jquery-image-swap/index.html
这是工作演示的链接http://micahcarrick.com/code/jquery-image-swap/index.html
I have tried to resolve this on my own. This is the first question I have had to ask so far regarding the building of my website, all my learning and remedies to past problems have been served by Google, this one has eluded my search engine skills.
我试图自己解决这个问题。这是我迄今为止关于网站建设的第一个问题,我所有的学习和对过去问题的补救措施都由 Google 提供,这个问题已经超出了我的搜索引擎技能。
Below I have added all the html for the page in case there may be other script overriding the "new" modified JavaScript -
下面我添加了页面的所有 html,以防可能有其他脚本覆盖“新”修改的 JavaScript -
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org /TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Cupcakes & Cakes for Birthday/Wedding Gift in Bournemouth Dorset - SweetVision</title>
<meta name="keywords" content="cupcakes, cake, gift, wedding, birthday, Bournemouth, Dorset" />
<meta name="description" content="For the finest Cupcakes and Cakes in Bournemouth Dorset look no further, Sweetvision specialise in baked goods for Weddings, Birthdays, Baby Showers, Easter, Halloween, Christmas" />
<meta name="robots" content="ALL" />
<meta http-equiv= "Content-Language" content="en" />
<meta name="Publisher" content="Sweet Vision" />
<meta name="Copyright" content="Copyright 2012, Sweet Vision, All rights reserved." />
<meta name="Author" content="Mark Webb for Sweet Vision - www.sweetvision.co.uk" />
<link href="../images/homepage/favicon.ico" type="image/vnd.microsoft.icon" rel="shortcut icon" />
<link href="../root/css/sweetvision.css" rel="stylesheet" type="text/css" />
<script src="../js/jquery-1.4.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.galleryicon').live("click", function(e) { // the (e) represent the event
$('#mainImage').hide();
$('#cakebox').css('background-image', "url('ajax-loader.gif')");
var i = $('<img />').attr('src',this.href).load(function() {
$('#mainImage').attr('src', i.attr('src'));
$('#cakebox').css('background-image', 'none');
$('#mainImage').fadeIn();
});
e.preventDefault(); //Prevent default click action which is causing the
return false; //page to scroll back to the top
});
});
</script>
<script src="../js/s3Slider.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#s3slider').s3Slider({
timeOut: 4000
});
});
</script>
<script src="../js/SpryMenuBar.js" type="text/javascript"></script>
<link href="../root/css/SpryMenuBarHorizontal.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
<div class="sprybox">
<ul id="check_menu" class="MenuBarHorizontal">
<li><a href="../root/index.html">Home</a></li>
<li><a href="../root/aboutus.html" class="MenuBarItemSubmenu">About Us</a>
<ul>
<li><a href="../root/contactus.html">Contact</a></li>
<li><a href="../root/news.html">News</a></li>
<li><a href="../root/events.html">Events</a></li>
</ul>
</li>
<li><a href="../root/ourmenu.html">Our Menu</a></li>
<li><a href="gallery.html">Gallery</a></li>
</ul>
<div class="mainmenu">
<a href="../root/mainmenu.html">
<img src="../images/buttons/mainmenu.png" />
</a>
</div>
<div class="backbutton">
<a href="javascript:history.go(-1)">
<img src="../images/buttons/Backbutton.png" /></a>
</div>
</div> <!-- end.header --><!--end of sprybox -->
<!--end div element -->
<!-- thumbnails are links to the full size image -->
<div class="cakecont">
<div id="cakebox">
<img src="../images/cakes/babycake1.png" alt="Main Image" id="mainImage"/>
<div class="pageinfo2">
<h3>Cake Type 1</h3>
<h6>£2.00</h6>
</div>
<div class="infobox">
<h6> Description </h6>
</div>
<div class="gallerybox">
<a href="../images/cakes/babycaketop.png" class="galleryicon">
<img src="../images/thumbs/babycaketopsml.png" alt="Thumbnail 2"/></a>
<a href="../images/cakes/babycake1.png" class="galleryicon">
<img src="../images/thumbs/babycakesml.png" alt="Image 1"/></a>
</div>
</div>
</div>
<div class="footer">
<p>Copyright © 2012 by Mark Webb. All rights reserved.</p>
</div> <!-- end .footer -->
</div> <!-- end .container -->
<script type="text/javascript">
var MenuBar1 = new Spry.Widget.MenuBar("check_menu",{imgDown:"SpryAssets/SpryMenuBarDownHover.gif", imgRight:"SpryAssets/SpryMenuBarRightHover.gif"});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-29457683-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</body>
</html>
回答by Briguy37
You can save the current scroll amount and then set it later:
您可以保存当前滚动量,然后再进行设置:
var tempScrollTop = $(window).scrollTop();
..//Your code
$(window).scrollTop(tempScrollTop);
回答by Nasser Al-Wohaibi
For all who came here from google and are using an anchor element for firing the event, please make sure to void the click likewise:
对于所有从谷歌来到这里并使用锚元素触发事件的人,请确保同样取消点击:
<a
href='javascript:void(0)'
onclick='javascript:whatever causing the page to scroll to the top'
></a>
回答by Mark Walters
Try the code below to prevent the default behaviour scrolling back to the top of the page
尝试以下代码以防止默认行为滚动回页面顶部
$(document).ready(function() {
$('.galleryicon').live("click", function(e) { // the (e) represent the event
$('#mainImage').hide();
$('#cakebox').css('background-image', "url('ajax-loader.gif')");
var i = $('<img />').attr('src',this.href).load(function() {
$('#mainImage').attr('src', i.attr('src'));
$('#cakebox').css('background-image', 'none');
$('#mainImage').fadeIn();
});
e.preventDefault(); //Prevent default click action which is causing the
return false; //page to scroll back to the top
});
});
For more information on event.preventDefault() have a look hereat the official documentation.
有关 event.preventDefault() 的更多信息,请查看官方文档。
回答by redlena
What you want to do is prevent the default action of the click event. To do this, you will need to modify your script like this:
您要做的是阻止单击事件的默认操作。为此,您需要像这样修改脚本:
$(document).ready(function() {
$('.galleryicon').live("click", function(e) {
$('#mainImage').hide();
$('#cakebox').css('background-image', "url('ajax-loader.gif')");
var i = $('<img />').attr('src',this.href).load(function() {
$('#mainImage').attr('src', i.attr('src'));
$('#cakebox').css('background-image', 'none');
$('#mainImage').fadeIn();
});
return false;
e.preventDefault();
});
});
So, you're adding an "e" that represents the event in the line $('.galleryicon').live("click", function(e) {
and you're adding the line e.preventDefault();
因此,您要添加一个“e”来表示该行中的事件,$('.galleryicon').live("click", function(e) {
并且您要添加该行e.preventDefault();
回答by olekeh
I had a similar problem getting scrollTop to work after reload of div content. The content scrolled to top each time the procedure below was run. I found that a little delay before setting the new scrolltop solved the issue.
在重新加载 div 内容后,我遇到了类似的问题,让 scrollTop 工作。每次运行以下过程时,内容都会滚动到顶部。我发现在设置新的 scrolltop 之前有点延迟解决了这个问题。
This is cut from wdCalendar where I modified this procedure:
这是从 wdCalendar 剪下来的,我修改了这个程序:
function BuildDaysAndWeekView(startday, l, events, config)
....
var scrollpos = $("#dvtec").scrollTop();
gridcontainer.html(html.join(""));
setTimeout(function() {
$("#dvtec").scrollTop(scrollpos);
}, 25);
....
Without the delay, it simply did not work.
没有延迟,它根本不起作用。
回答by Daniel Dewhurst
Something to note, when setting the scroll position, make sure you do it in the correct scope. For example, if you're using the scroll position in multiple functions, you would want to set it outside of these functions.
需要注意的是,设置滚动位置时,请确保在正确的范围内进行。例如,如果您在多个函数中使用滚动位置,您可能希望将其设置在这些函数之外。
$(document).ready(function() {
var tempScrollTop = $(window).scrollTop();
function example() {
console.log(tempScrollTop);
};
});
回答by Danh V?n V?
$('html,body').animate({
scrollTop: $('#answer-<%= @answer.id %>').offset().top - 50
}, 700);