Problem with HTML anchor in absolute DIV 300px from the top..?
I have a page with a header position:fixed DIV at the top . This DIV is height:300px and it is fixed so that it's always visible even when users scroll down.
My content is in another DIV below. It has a position:absolute with a top:300px . So when you first load the page, it starts below my header and when you scroll, it scroll underneath my header which stays fixed at the top.
In my content DIV, I have multiple anchor. When I click a link to one of these anchor, the page scrolls but places the anchor right at the top of the page. So basically, the content that was supposed to be displayed is hidden under my header...
Do you have any idea how to fix this problem with HTML/CSS..?
Is there another solution apart from using iframe or a frameset..?
You can do it with jquery.
First you need to include the jquery library in you <head>
f you aint already.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
under the above you need the following javascript
<script type="text/javascript">
$(function(){
$('a[href*=#]').click(function() {
if (location.pathname.replace(/^//,'') == this.pathname.replace(/^//,'')
&& location.hostname == this.hostname) {
var $target = $(this.hash);
$target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
if ($target.length) {
var targetOffset = $target.offset().top - 300;
$('html,body').animate({scrollTop: targetOffset}, 10);
return false;
}
}
});
});
</script>
The following line from the above script controls the offset, or 'margin' from the top.
var targetOffset = $target.offset().top - 300;
You can also make the scroll smooth by increasing the value on this line.
$('html,body').animate({scrollTop: targetOffset}, 10);
try replacing it with this.
$('html,body').animate({scrollTop: targetOffset}, 1000);
Padding and negative margins should work on this. Here's an example page to preview: http://jsbin.com/ucili/edit
Essentially, for the anchors, I have a padding-top of 300px and a margin-top of -300px. The padding makes sure the anchor doesn't fall under the fixed div, the negative margin makes it so the content flows correctly (without huge gaps of white space).
这个例子使用了padding- / margin-top技巧,但是通过CSS3伪类实现:target
:
/* assuming the header-height is 8em */
:target {
padding-top: 8em;
margin-top: -8em; }
链接地址: http://www.djcxy.com/p/62044.html
上一篇: 更改#anchor的默认开始位置