Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/390.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Jquery更改位置,然后滚动到元素_Javascript_Jquery - Fatal编程技术网

Javascript Jquery更改位置,然后滚动到元素

Javascript Jquery更改位置,然后滚动到元素,javascript,jquery,Javascript,Jquery,当我在index.php上并按下home按钮时,它会向下滚动到元素。但是,当我不在index.php上并按下相同的按钮时,我想更改URL位置,然后滚动到元素。我就是这样尝试的: $('.home').on('click', function (event) { // If location is index.php do this: if (location.href.indexOf("/index.php") > -1) { $('html, body

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

$('.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);
    }
});

它只是更改url,但当我不在索引上时,它不会滚动到元素。php使用哈希而不是使用jQuery滚动到某个元素

  • 将哈希添加到URL
    http://www.myurl.com/index.php#anotherelement
  • 在要在页面加载时滚动的页面中添加具有相同id的元素(
    anotherelement

  • 请将您的代码更改为

    $('.home').on('click', function (event) {
        if (location.href.indexOf("/index.php") > -1) {
            $('html, body').animate({
                scrollTop: $("#anotherelement").offset().top
            }, 1000);
    
        } else {
            window.location = "index.php#anotherelement";
        }
    });
    

    当您更改加载新页面的位置时,您需要在dom ready函数上使用它(滚动效果),这样您的滚动代码就没有用了,因为您是从“上一页”开始执行的。这是正确的,但是没有任何动画。这可以在新加载的页面上使用
    hashchange
    事件来处理,但显然这符合OP的需要:)