2013-09-30 165 views
3

我使用这个脚本打开一个模式:的jQuery:自动滚动到顶部

<script type="text/javascript"> 
$(function(){ 
$('.compose').click(function() { 
    $('#popup_bestanden_edit_name').reveal({ 

     animation: 'fade', 
     animationspeed: 600, 
     closeonbackgroundclick: true, 
     dismissModalClass: 'close', 
      }); 
    return false; 
}); 
}); </script> 

但是,当我在页面的底部,并点击链接,该模式在页面的顶部打开。 所以它看起来没有任何事情发生,但我必须滚动到顶部才能看到打开的模式。

当模式打开时,是否可以自动将用户发送到顶端?下面的代码

+0

岂不是更好的解决方案,以看到它的模式,在当前文件位置打开,而不是强迫的页面,使得用户不得不回到他们的位置向上滚动之前...? – CBroe

+0

是的,你是对的。但我不知道如何解决这个问题。但那也是一个选择。 –

+0

问题修复!请参阅: 刚刚在此处添加CSS:http://jsfiddle.net/mondico/et47L/1/ 我将位置:绝对修改为固定。这样做的工作! 谢谢! –

回答

2

你可以添加position: fixed,例如top: 30px添加到样式#popup_bestanden_edit_name。如果你这样做,无论用户在页面上的哪个位置,模态都会出现在同一个地方。但是你必须小心,因为如果模态高于视口,你将无法看到模态的剩余部分。

如果你仍然要滚动到顶部(不包括动画),使用JavaScript就可以把

$('body').scrollTop(0); 

之前你return false;

权顺便说一句,如果你想阻止一个链接的默认动作火,这是一个更好的做法,这样做:

$('.compose').click(function(event) { 
    // your code here 
    event.preventDefault(); 
} 
+0

我知道,但多数民众赞成在问题。 模态已经固定在顶部,但那不是我想要的。 原因'当我在页面的底部,我打开模式,它打开在顶部,我看不到它,除非我滚动到页面的顶部。 –

+0

“位置:固定”与“位置:绝对”相混淆。 – lort

9

使用移动到页面的顶部:

$('html, body').animate({scrollTop: '0px'}, 0); 

而不是0,你可以有一些其他的价值像500(它以毫秒为单位),使其移动到慢慢顶部

+0

谢谢U, 我试过了,但我不知道在哪里把它,或者怎么样,看我的例子: http://jsfiddle.net/mondico/et47L/ 这不是完整的,但我没有说明我是如何把它放在jQuery .. 但我不明白如何去做。 –

+0

问题解决了。看到我对我的startpost的评论。 –

+0

好的人像魅力一样工作 –

0

我会建议不滚动到页面的顶部。这是不好的用户体验设计!我们可以在身体上隐藏溢出。所以,一旦弹出窗口进入屏幕,用户不能滚动。我们需要给位置固定的弹出框的主要元素。

我建议检查下面的代码片段。

<html> 
    <head> 
     <title>Example</title> 
     <style type="text/css"> 
      .nooverflow {overflow: hidden;} 
      .popup {position: fixed; z-index: 99;} 
      .cover {position: fixed; background: #000; opacity: .5; filter: alpha(opacity=50); top: 0; left: 0; width: 100%; height: 100%; z-index: 1000; } 
      .popup-conteiner {overflow-y: auto; position: fixed; height: 100%; width: 100%; left: 0; top: 0; z-index: 101;} 
      .popup-block {position: relative; top: 100px; z-index: 101;} 
     </style> 
    </head> 
    <body> 
     <div id="popup"> 
      <div class="cover"></div> 
      <div class="popup-conteiner"> 
       <div class="popup-block"> 
        <!-- POPUP's HTML GOES HERE --> 
       </div> 
      </div> 
     </div> 
    </body> 
</html> 

但是,如果它不起作用,那么你可以滚动页面到页面的顶部。您也可以使用Rajesh给出的解决方案。我想添加一个条件,如果页面已经动画,然后停止之前做新的动画。

var htmlBody = $("html,body"), 
    top = 0; 

if (htmlBody.is(':animated')) { 
    htmlBody.stop(true, true); //Need to stop if it is already being animated 
} 

htmlBody.animate({ scrollTop: top }, 1000); //Scroll to the top of the page by animating for 1 sec. 
+0

谢谢你,我现在通过将CSS设置为FIXED而不是ABSOLUTE来解决问题。 这使得弹出窗口在用户在那个时刻的文档位置打开。 –

+0

我很高兴你找到了解决方案。我也喜欢动画方法滚动到给定的顶部。确保停止(http://api.jquery.com/stop/)或出列(http://api.jquery.com/dequeue/)动画以避免出错的影响。 –

+0

我通过在DOM节点上使用scrollIntoView来解决Chrome问题,想要滚动到顶部的容器顶部的项目,比如标题。 – Epirocks