使用网址滚动到某个div

时间:2012-06-17 12:34:03

标签: javascript jquery

我可以发送请求加载某个div的URL只有像abc.com/#header1这样的东西导致我正在使用的方法我必须为我的任务制作5个单独的文件并更新所有这些文件。 如果可以通过在我的一个文件中包含任何代码来完成,那么它对我来说是最好的。

我希望div上的滚动带有url请求,例如abc.com/#def,其中def是页面应该加载的div的id。

3 个答案:

答案 0 :(得分:4)

关于你的previous question,你可以这样做:

$(function(){
  // get hash value
  var hash = window.location.hash;
  // now scroll to element with that id
  $('html, body').animate({ scrollTop: $(hash).offset().top });
});

您需要将该代码放在要滚动元素的页面中。因此,如果您访问yourdomain.com/#foo,则会滚动到id设置为foo的元素。

答案 1 :(得分:2)

您可以使用jQuery在页面中的特定div中加载一些URL。

 Here is an example with fraction of code :    
 $('#result').load('test.html', function() {
   alert('Hello,I am in the div');
});

如果您需要显示该特定网址的数据。那么,您可以将Ajax与Jquery一起使用。

   Here is a small code for it:
  $(document).ready(function(){
     $("#result").load(function(){

          $.ajax({
            type: 'GET',
            url: "http://localhost/a.html",
            success:function(data){
             alert(data);
            }
        });
    return false;
   });
});

希望这会对你有所帮助。

答案 2 :(得分:0)

试试这个:document.getElementById('elmID')。scrollIntoView(true);