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

编程入门 行业动态 更新时间:2024-10-25 18:23:35
本文介绍了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.

  • 将哈希添加到URL www.myurl/index.php#anotherelement
  • 在要在页面加载时滚动的页面中添加具有相同ID的元素(在此示例中为 anotherelement )。
  • Add the hash to the URL www.myurl/index.php#anotherelement
  • Add the element with the same id(anotherelement in this example) in the page where you want to scroll on page load.
  • 更多推荐

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

    本文发布于:2023-10-07 23:47:30,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1470881.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:元素   位置   Jquery

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!