Py学习  »  Jquery

Jquery仅在重定向后向下滚动

yonea • 3 年前 • 1180 次点击  

我有一页产品列表,带有返回按钮,可以重定向到主页。 我想在重定向到主页后,向下滚动到一个特定的div(在我的例子中,是一个产品旋转木马)

我做了滚动,但每次加载主页时它都会工作,但我只想在点击返回按钮后滚动,请问我该怎么做?

这里有一些代码:

产品页面列表:

<a href="{{ path('home_index') }}" class="return-ad">
    <img src="{{ app.request.getBaseURL()/arrow-white-left.png">
</a>

主页:

<div class="row align-items-stretch">
     Some code here
</div>

<script>
    $(".return-ad").ready(function() {
        $('html,body').animate({
                scrollTop: $(".align-items-stretch").offset().top},
            1000);
    });
</script>

有人能帮我吗?我是Jquery和JS的新手

提前谢谢

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/129628
 
1180 次点击  
文章 [ 1 ]  |  最新文章 3 年前
Rory McCrossan
Reply   •   1 楼
Rory McCrossan    3 年前

为了实现这一点,您可以在URL中添加一个片段,当主页下次加载时可以检测到该片段:

在产品页面中添加 # 链接到URL的片段:

<a href="{{ path('home_index') }}#foo" class="return-ad">
  <img src="{{ app.request.getBaseURL()/arrow-white-left.png">
</a>

然后在主页中,检测该片段并执行动画:

jQuery($ => {
  if (window.location.hash && window.location.hash.substring(1) === 'foo') {
    $('html,body').animate({
      scrollTop: $(".align-items-stretch").offset().top
    }, 1000);  
  }
});

还要注意 ready() 方法应在 document ,而不是DOM中的元素。我修改了上面的例子,使用了a的缩写形式 document.ready 事件处理程序