为页面转换创建链接

时间:2016-09-17 09:35:05

标签: javascript html css

我正在写一个单页网站。它有3个'幻灯片',如关于/音乐/联系。使用下拉菜单创建对这些幻灯片的访问。当您单击菜单中的链接时,当前页面包装器将转到visibility: hidden并通过动画可以看到以下内容。这很好用,但一切都发生在根页面上,而不更改URL,这不是用户友好的,就好像你想要共享链接到页面,你将始终被重定向到根。

所以问题是:“如何在不重新加载页面的情况下更改网址(可能通过哈希或smth)?”。提前谢谢。

P.S。不需要代码,只需告诉我你的方法,我会将其添加到代码中。

1 个答案:

答案 0 :(得分:0)

只需检查一下,如果你想要这个就拿走它

function isElementInViewport (el) {
      //special bonus for those using jQuery
      if (typeof jQuery === "function" && el instanceof jQuery) {
        el = el[0];
      }
      var rect = el.getBoundingClientRect();
      return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
        rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
      );
    }


    // click-to-scroll behavior
    $("a").click(function (e) {
      e.preventDefault();
      var section = this.href;
      var sectionClean = section.substring(section.indexOf("#"));
      $("html, body").animate({
        scrollTop: $(sectionClean).offset().top
      }, 1000, function () {
        window.location.hash = sectionClean;
      });
    });
    
    // listen for the scroll event
    $(document).on("scroll", function() {
      //console.log("onscroll event fired...");
      // check if the anchor elements are visible
      $(".common").each(function (idx, el) {
        if ( isElementInViewport(el) ) {
          // update the URL hash
          if (window.history.pushState) {
            var urlHash = "#" + $(el).attr("id");
            window.history.pushState(null, null, urlHash);
          }
        }
      });
    });
body {
  float: left;
  width: 100%;
  padding-bottom: 0px;
 
}
.common {
	width: 100%;
	float: left;
	height: 100vh;
	display: table;
}
.allbody {
	float: left;
	width: 100%;
}

a {
	display: inline-block;
	padding: 15px;
}
header {
	float: left;
	width: 100%;
	position: fixed;
	top: 0;
	left: 0;
	background: #fff;
}
.common h2 {
	font-size: 30px;
	color: #fff;
	text-align: center;
	padding-top: 10%;
	display: table-cell;
	vertical-align: middle;
}
#firstDestination {
	background: #000;
}
#secondDestination {
	background: #999;
}
#thirdDestination {
	background: #ccc;
}
#fourthDestination {
	background: #c1c1c1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<header>
	<a href="#firstDestination">first page</a>
	<a href="#secondDestination" >second page</a>
	<a href="#thirdDestination">third page</a>
	<a href="#fourthDestination">fourth page</a>
</header>


<div class="allbody">
	<div class="common" id="firstDestination" ><h2>First Page</h2></div>
	<div class="common" id="secondDestination"><h2>Second Page</h2></div>
	<div class="common" id="thirdDestination" ><h2>Third Page</h2></div>
	<div class="common" id="fourthDestination" ><h2>Fourth Page</h2></div> 

</div>