[英]Using AJAX to load page into a div at a specific anchor
I've seen a few questions on here related to this, but I'm not seeing the exact situation I'm talking about so I figured I'd ask. 我在这里看到了与此相关的一些问题,但是我没有看到我正在谈论的确切情况,所以我想问一下。
I have a page with two divs. 我有一个包含两个div的页面。 A sidenav div (
sidediv
) and a main body ( maindiv
) div. 一个sidenav div(
sidediv
)和一个主体( maindiv
)div。
What I want: To click a link in the side nav to load a page in the main div. 我想要的是:单击侧面导航栏中的链接以在主div中加载页面。 At the moment, anyway, it's always the same page, but it's a huge page with several anchors.
无论如何,此刻始终是同一页面,但它是一个包含多个锚点的巨大页面。 The items in the side link to varied anchors.
侧面的项目链接到各种锚点。
What I'm doing: My sidenav links look like so: 我在做什么:我的sidenav链接如下所示:
<a href="#" onclick="loadPage('mypage.html#ds'); return false;">Desired Section</a>
and the JS: 和JS:
function loadPage(url){
var xhr= new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange= function() {
if (this.readyState!==4) return;
if (this.status!==200) return;
document.getElementById('maindiv').innerHTML= this.responseText;
};
xhr.send();
}
What happens: It loads mypage.html just fine, but refuses to go to the anchor. 发生的情况:可以很好地加载mypage.html,但拒绝定位。
How do I make that happen (sans jQuery, BTW, I currently am not using it on site and don't feel like loading it in for one thing) 我如何做到这一点(没有jQuery,BTW,我目前不在网站上使用它,也不希望一件事将其加载进来)
Thanks. 谢谢。
Ok this was interesting so I took a shot at it for you. 好的,这很有趣,所以我为您拍摄了照片。 Here is what I came up with.
这是我想出的。 It uses
scrollIntoView
. 它使用
scrollIntoView
。 Also keep in mind that I simulated the ajax call so my loadPage
function does some stuff differently than you will. 还要记住,我模拟了ajax调用,因此我的
loadPage
函数所做的某些事情与您所做的有所不同。
var pages = { 'mypage.html': '<div id="ts" class="page">my stuff</div><div id="ds" class="page">my more stuff</div><div id="eds" class="page">my even more stuff</div>', 'yourpage.html': '<div id="ts" class="page">your stuff</div><div id="ds" class="page">your more stuff</div><div id="eds" class="page">your even more stuff</div>' }; function loadPage(url) { var set = url.split('#'), page = set[0], id = set[1]; // simulate xhr request setTimeout(function() { document.getElementById('maindiv').innerHTML = pages[page]; document.getElementById(id).scrollIntoView(); }, 1000); }
.page { height: 400px; } .menu { width: 200px; float: left; position: fixed; } #maindiv { width: 50px; float: right; background: lightblue; }
<div class="menu"> <a href="#" onclick="loadPage('mypage.html#ds'); return false;">My Page #ds</a><br /> <a href="#" onclick="loadPage('yourpage.html#eds'); return false;">Your Page #eds</a> </div> <div id="maindiv"> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.