Jquery更改位置然后滚动到元素 [英] Jquery change location then scroll to element

查看:79
本文介绍了Jquery更改位置然后滚动到元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在index.php上并按下主页按钮时,它向下滚动到元素。但是,当我不在index.php上并按下相同的按钮时,我想更改URL位置,然后滚动到该元素。这就是我尝试的方式:

When I am on the index.php and press the home button, it scroll down to the element. However, when I'm not on the index.php and press the same button, I want to change the URL location, then scroll to the element. This is how I tried:

$('.home').on('click', function (event) {

    // If location is index.php do this:
    if (location.href.indexOf("/index.php") > -1) {

        $('html, body').animate({
            scrollTop: $("#anotherelement").offset().top
        }, 1000);

        // If location is not index.php do this:
    } else {
        window.location = "index.php";

        $('html, body').animate({
            scrollTop: $("#anotherelement").offset().top
        }, 1000);
    }
});

它只是更改了网址但是当我不在索引时它不会滚动到元素.php

It just changes the url but it doesn't scroll to element when I'm not on the index.php

推荐答案

使用hash而不是使用jQuery滚动到某个元素。

Use hash instead of using jQuery to scroll to some element.


  1. 将哈希添加到URL http://www.myurl.com/index.php#anotherelement

  2. 在要在页面加载时滚动的页面中添加具有相同ID的元素(在此示例中为 anotherelement )。

  1. Add the hash to the URL http://www.myurl.com/index.php#anotherelement
  2. Add the element with the same id(anotherelement in this example) in the page where you want to scroll on page load.

这篇关于Jquery更改位置然后滚动到元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆