开发者

Use javascript to center anchor object when page loads

I want to jump to an anchor tag when my page loads AND开发者_如何学Go have the anchor object centered in the window. I've used a simple function to go to the anchor when the page loads:

<body onload="goToAnchor();">

<script type="text/javascript">

function goToAnchor() {
window.location = "#center";
}

</script>

But in order for the anchor object to be centered, I need to somehow offset the location of the window. For another function, I used something like this to achieve the appropriate offset (the width of the object is a fixed 1500px):

var $offset_target = (1500 - $(window).width())/2;

This successfully ensured that each time I jumped to an anchor, the object was centered in the viewport, regardless of the window size.

Any ideas?

Thanks!!

UPDATE/ANSWER

So, I used two of the replies below to come up with this:

function goToAnchor() {
document.body.scrollLeft = document.documentElement.scrollLeft =       
document.getElementById('center').offsetLeft-
(Math.ceil((- 1500 + $(window).width()) / 2));

}

It might not be the most elegant solution, but it gets the job done! Thanks so much for your answers!

If anyone has a better way to do this, please let us know!


Without jQuery:

function goToAnchor() {
    document.body.scrollTop = document.documentElement.scrollTop =
        document.getElementById('center').offsetTop-window.innerHeight/2;
}

This will work fine in most cases. If #center is located in an element with position other than static then it would need a bit extra to calculate the correct offset, but otherwise it'll work as is.


I did this for a website not too long ago, the code below uses the users window width and subtracts it from your static object's width, divides by two and scrolls horizontally to that location which will center the object horizontally.

$(window).scrollLeft(Math.ceil((1500 - $(window).width()) / 2));


You don't need script at all, use CSS:

.centered {
  text-align: left;
  width: 500px;
  margin-left: auto;
  margin-right: auto;
}

IE needs to be in standards mode for this to work (which just means using a valid DOCTYPE). Setting both margins to auto makes them have the same value.

Here's a full example that centers the body element:

<style type="text/css">
.centered {
  text-align: left;
  width: 500px;
  margin-left: auto;
  margin-right: auto;
  border: 1px solid blue;
}
.panel1 {border: 1px solid red;height: 200px}
.panel2 {border: 1px solid green;height: 200px}
</style>

<body class="centered">
  <div class="panel1">
    <div class="panel2"></div>
  </div>
  <div class="panel1">
    <div class="panel2"></div>
  </div>
</body>  
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜