When I jump to an anchor tag in on a wide (4000px) page, the anchored image is horizontally aligned to the right. How can I get it to align to the center? I have tried several things but none seem to w开发者_如何学运维ork. Since I am new here I am not allowed to post the code, so I hope I was clear enough.
Thanks for your help,
Robert C.
The issue arises because the browser will do the least amount of scrolling required to bring the anchored element into view. Thus, if it is off to the right of the viewable area, when the anchor tag is clicked, it will simply scroll far enough to the right to reveal the whole element.
You could fix this behavior with javascript if that is an option. You won't be able to center it on #anchor
click with straight CSS.
Here is a "solution" using jQuery. I have "solution" in quotes because it may introduce more problems than you want. For instance, without further JS the back button won't work to go to the previous link. But this does center the item given your sample code.
Just add this to the page you linked above before the closing <head>
tag:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("a[href^=#]").click(function(e){
var id = $(this).attr('href').substr(1),
$target = $('*[name=' + id + '] img'),
$window = $(window),
offset = $target.offset();
var left = offset.left - ($window.width() / 2) + ($target.width() / 2 );
var top = offset.top - ($window.height() / 2) + ($target.height() / 2);
$('html,body').scrollTop(top).scrollLeft( left);
e.preventDefault(); // Keep the browser from trying
});
});
</script>
It will find all a
tags with internal links (href starts with #
). Then it finds the target that has that name, and grabs the child img
tag. Then it gets the dimensions of the img
element and the window
element. Does some math with the img
elements offset, and scrolls it into center.
精彩评论