2014-12-07 78 views
0

我有一个带有一些部分的文档,其中包含需要根据URL定位点收集的信息。jQuery - 从更改页面位置停止网址定位点

的什么,我试图做例子:

URL

http://mywebsite.com/page.php#section-2

HTML

<div id='information'>Data should be here!</div> 

<div id='section-1'>This is data from section 1!</div> 

<div id='section-2'>This is data from section 2!</div> 

<div id='section-3'>This is data from section 3!</div> 

<div id='section-4'>This is data from section 4!</div> 

CSS

div{ 
    height: 500px; 
} 

jQuery的

var hash = window.location.hash; 
if(!hash == ""){ 
    var data = $(hash).text(); 
    $("#information").text(data); 
} 

但是当我加载URL,jQuery的工作正常,但页面跳转到#section-2
如何阻止这种情况发生?

在此先感谢。

回答

0

的顶部,我设法找到一种方法来解决它!
出于某种原因,时机搞砸了,并导致$('body').scrollTop(0);不起作用。

我可以通过在滚动到页面顶部之前添加10毫秒的延迟来修复它。

$(document).ready(function(){ 
    if(hash){ 
    setTimeout(function(){ 
     $('body').scrollTop(0); 
    }, 10); 
    } 
}); 
0

您的状况不正确。应该是!=

if(hash != ""){ 
    var data = $(hash).text(); 
    $("#information").text(data); 
} 

而为了防止跳跃,您可以尝试使用scrollTop()

$(document).ready(function(){ 
 
    var hash = window.location.hash; 
 
    if(hash){ 
 
    $('body').scrollTop(0); 
 
    } 
 
});
div{ 
 
    height: 500px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 
<div id='information'>Data should be here!</div> 
 

 
<div id='section-1'>This is data from section 1!</div> 
 

 
<div id='section-2'>This is data from section 2!</div> 
 

 
<div id='section-3'>This is data from section 3!</div> 
 

 
<div id='section-4'>This is data from section 4!</div>

+0

我想你误解了这个问题。我不需要帮助收集数据,我需要它来阻止页面跳转到锚点。 – Kain 2014-12-07 08:58:22

+0

看到编辑,也试过了。它仍然跳到锚点。 – Kain 2014-12-07 09:05:50

+0

您是否在'$(document).ready()'中放置了'scrollTop(0)'? – MH2K9 2014-12-07 09:07:03

0

我设法找到一种方法来解决它!
出于某种原因,时机搞砸了,并导致$('body').scrollTop(0);不起作用。

我可以通过在滚动到页面顶部之前添加10毫秒的延迟来修复它。

$(document).ready(function(){ 
    if(hash){ 
    setTimeout(function(){ 
     $('body').scrollTop(0); 
    }, 10); 
    } 
}); 
+0

我试过这个,但它似乎没有工作。该页面仍然跳转到锚点。 – Kain 2014-12-07 09:04:10

+0

你可以添加一个小提琴吗? – Anubhav 2014-12-07 09:04:33

+0

我将无法摆弄代码。你需要添加一个演示。 – Anubhav 2014-12-07 09:07:10

0

如果页面中存在id = hash的可见div,浏览器将跳转。防止这种情况的一种方法是设置你的div显示=无在CSS所以它们不是页面加载时可见,然后将它们变为可见

$(function() { 
    $('div').show(); 
}); 

后立即或者你可能只想显示在一个部分一时间..

$(function() { 
    $('#section-2').show(); 
}); 

另一种可能是留下明显的div但马上回滚动到页面

$(function() { 
    self.scrollTo(0, 0); 
}); 
+0

不幸的是我需要显示div。我试过'self.scrollTo(0,0);'但是和其他答案一样,它似乎不起作用。我不知道什么是阻止它:/ – Kain 2014-12-07 09:18:26

+0

我已经发布了答案,在滚动之前的一个简单的10毫秒延迟。 - 见答案 – Kain 2014-12-07 09:28:24