单击时,命名锚点书签始终显示在屏幕顶部

时间:2012-09-02 17:17:35

标签: javascript jquery html css

我的标记如下:

<li><a href="#sheds_housing">Sheds &amp; Housing</a></li>
<div id="sheds_housing">
    <h1>sheds &amp; housing</h1>
    <img src="images/cattle/sheds_housing.png" width="150" height="150" alt="Sheds & Housing"
        title="Sheds & Housing" />
    <p>Text here</p>
</div>

创建指向页面某个部分的链接,这样当用户点击该锚点时,就会将他带到该部分。

无论如何,我可以确保当用户这样做时,内容始终显示在顶部,而不会在链接div上方的文档的正常流程中出现任何额外内容。

可以单独用CSS完成,还是必须使用JS / jQuery,如果是的话是什么代码?

修改

我以前不清楚;见Fiddle。如果您单击前两个链接,您将进入相应的部分,内容将显示在窗口的顶部,但如果您单击最后一个链接,您将被带到相应的部分,但内容不会出现在窗口的顶部和位于相应部分上方的内容存在。

12 个答案:

答案 0 :(得分:4)

将id“last_anchor”添加到列表中的最后一个链接,这将通过jquery实现。如何以及如果你决定改变身体的边缘取决于你......

$(document).ready(function(){
  $("#last_anchor").click(function(){
    var content_id = $(this).attr("href");
    var win_height = $(window).height();
    var content_height = $(content_id).height();
    var target_margin = win_height - content_height;
    $("body").css("margin-bottom", target_margin)
  });
});​

答案 1 :(得分:2)

  

内容始终显示在顶部,没有任何额外内容可能出现在链接div上方文档的正常流程中。

假设这意味着您要隐藏页面上的所有部分,只显示与所点击的链接相对应的部分,您要查找的部分称为Accordian,您可以找到一个样本here

答案 2 :(得分:2)

问题是(如果我理解正确的话!)你正在点击页面的末尾。 如果你扩展最后一个元素的边距或添加一些内容,标题将显示在顶部(如果有足够的页面显示)。

见小提琴: http://jsfiddle.net/tHXsS/

答案 3 :(得分:2)

解决方案: http://jsfiddle.net/AdKy9/2/

将此添加到您的代码中:

<!-- 
  padding div tag goes AFTER #med_vac
  but BEFORE closing tag of #content
-->
<div id="lowerPadding"></div>

<!-- script tag goes in <head> -->

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">

  $(document).ready(function() {
    $("a").click(function() {
      var targ = $(this).attr('href');
      var elem = $(targ);
      document.location.href= targ;
      assureAtTop(elem);
      document.location.href= targ;
    });
  });


  function assureAtTop(inObj) {
    var y = $(inObj).height();
    var z = $("#lowerPadding").height();
    var w = $(window).height();
    while (y+z < w) {
      $("#lowerPadding").append("<br/>");
      z = $("#lowerPadding").height();
    }
  }

</script>
  • 点击<a>元素,转到位置。
  • 获取目标位置,填充标记和窗口的高度。
  • <br/>标记添加到填充标记,直到目标位置位于窗口顶部

    注意:检查所有<a>标记,因为如果窗口具有较大的垂直高度和/或较大的水平宽度,则第二个甚至第三个目标位置可能需要填充。这也可以在没有jQuery的情况下实现,但使用jQuery只是更容易和跨浏览器。

答案 4 :(得分:2)

我解决问题的初步解决方案与上面的@ saurabh相似:

http://jsfiddle.net/Cgx3h/

$('.sub_navi a').click(function() {
    var theID = $(this).attr('href');
    $(theID+':last-child').css('min-height', $(window).height());
})

如果您最终使用jQuery,您可能会考虑的其他事项是突出显示重点内容 - 同时调整其余内容......

http://jsfiddle.net/hZGwA/

$('.sub_navi a').click(function() {
    $('#content div').css('opacity',0.5);
    var theID = $(this).attr('href');
    $(theID).css('opacity', 1);
})

答案 5 :(得分:2)

这就是我所做的:

  1. 用户向下滚动页面。
    没有任何异常情况发生(页面没有变化)。

  2. 用户点击/使用您的主播。
    代码在#content之后创建一些空格,因此它可以将所需的部分放在屏幕顶部。

  3. 用户将页面向上滚动到div内的第一个#content(可能是您喜欢的任何一个点)或点击后退按钮转到页面顶部
    空白区域消失(您的页面恢复正常)。

  4. 在线测试:http://jsfiddle.net/RASG/z3q3s/

    或者将此代码保存为HTML文件,以便在您的电脑上进行测试:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    
    <head>
        <script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
        <script>
        $(document).ready(function() {
            function isScrolledIntoView(elem){
                var docViewTop = $(window).scrollTop();
                var docViewBottom = docViewTop + $(window).height();
    
                var elemTop = $(elem).offset().top;
                var elemBottom = elemTop + $(elem).height();
    
                return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
            }
    
            var elem_that_hides_dummydiv = $('#content div:first');
            var elem_that_shows_dummydiv = $('#content div:last');
            $(window).scroll(function() {
                if (isScrolledIntoView(elem_that_hides_dummydiv)) { $('#dummydiv').hide() }
            });
            $('#gonnaclickhere').click(function() {
                $('#dummydiv').css({'height':(elem_that_shows_dummydiv.offset().top)+'px'}).show()
            })
        });
        </script>
    </head>
    
    <body>
    
    <ul class="sub_navi">
        <li><a href="#sheds_housing">Sheds &amp; Housing</a></li>
        <li><a href="#feed_fodder">Feed &amp; Fodder</a></li>
        <li id="gonnaclickhere"><a href="#med_vac">Medication &amp; Vaccination</a></li>
    </ul>
    
    <div id="content">
    
        <div id="content_pic">
        <img src="images/cattle/cattle_main.jpg" width="400" height="300" alt="Cattle Main" title="Cattle Main" />
        </div>
    
        <p>Pak United Food Services Ltd., (PUFS) has earned a creditable name and become a major player in the animal husbandry market by building upon Pakistan&apos;s large livestock population. Introducing the concept of corporate cattle farming on scientific lines, the conglomerate uses a livestock development policy consisting of innovative strategies and action plans with the intention of bringing about a radical change in the current livestock production system. The cattle farms are established on rich and fertile acres of land and consist of an impressive and mixed herd of cows/buffalos and sheep/goats.</p>
        <p>A hybrid meat breed is developed by crossing the local indigenous breeds which are predominately draught/milch animals with high meat yielding animals from other parts of the world. A herd management system is incorporated to improve record keeping and obtain information for bench marking decisions. The farms employ a state of the art feedlot design involving the integration of the standard components into a fully functional operating system. This consists of housing, feeding, watering, health-care and cattle effluent &amp; manure management systems, making them well known across the country.</p>
    
        <div id="sheds_housing">
        <h1>sheds &amp; housing</h1>
        <img src="images/cattle/sheds_housing.png" width="150" height="150" alt="Sheds & Housing" title="Sheds & Housing" />
        <p>The housing for the animals utilizes a proper lay out for the farm buildings while keeping in view the environment, climate and wind direction. Sheds, pens and paddocks are constructed according to different categories and sex groups besides other infrastructure &amp; allied facilities. All buildings are made airy for the protection of the animals from extreme temperatures and strong winds. Adequate supply of water for drinking and cleaning is made necessary with strict maintenance of hygienic conditions. Ample sunlight and natural ventilation is assured to assist in the reduction of moisture and bacteria, offering a healthier, cleaner &amp; drier environment while also reducing the risk of disease and mortality in the livestock.</p>
        </div>
    
        <div id="feed_fodder">
        <h1>feed &amp; fodder</h1>
        <img src="images/cattle/feed_fodder.png" width="150" height="150" alt="Feed & Fodder" title="Feed & Fodder" />
        <p>The farms are equipped with in-house feed formulation capabilities which produce feed of constant quality and are palatable, nutritious and free from contamination. Feed supplies are made available according to different feed formulae while keeping in view the nutrient value and energy levels. Daily requirements are worked out for each category and class to achieve improved growth &amp; overall health. A restricted feeding regime is employed that is balanced &amp;amp; concentrated, containing minerals &amp; vitamins, leading to an improved feed/gain ratio. Fodder &amp; wheat/rice straws are purchased/contracted from the nearest markets, while treating it with ammonia or urea to improve the quality and gain a marked effect on cattle weight during the fattening period.</p>
        </div>
    
        <div id="med_vac">
        <div id="med_vac_title">
        <h1>medication &amp; vaccination</h1>
        </div>
        <img src="images/cattle/med_vac.png" width="150" height="150" alt="Medication & Vaccination" title="Medication & Vaccination" />
        <p>Regular vaccination of the whole herd against contagious and infectious diseases are carried out as a prophylactic measure in order to make sure that the animals are free of diseases of digestive, respiratory, urinary, gynecological and obstetrics by a designated veterinarian. A proactive health plan in employed to improve the health, welfare and productivity of the animals. A pre-weaning vaccination program is used with correct, effective and proper vaccines, dewormers, antibiotics and other medications to prime the immune systems of the animals. Furthermore post-weaning vaccination program is used to boost the immune system of the animals and increase the passive protection against common endemic livestock diseases.</p>
        </div>
    
    </div>
    
    <div id='dummydiv' style="bottom: 0; width: 100%;"></div>
    
    </body>
    
    </html>
    

    使用FF13和IE9进行测试。

答案 6 :(得分:1)

您需要将导航与另一个div包装在一起,以便您可以将CSS应用于整个导航。完成后,您可以将标题定位到固定位置。下一步是通过将页面内容向下移动一些(导航高度)为页面顶部的常量标题腾出空间。为此,将所有内容包装在另一个div中(不包括导航)在这个内容div)并应用一些CSS - margin-top: (height of nav);

#topnav
{
    position: fixed;
}

#content
{
    margin-top: (height of nav);
}

编辑:

啊,好吧,我明白你想要什么。为了实现这一点,您可以设置div的高度或者当您转到锚点时使用min-height进行所有潜水,它们将是底部的空间,以便浏览器向下滚动到。

因此,您必须在CSS中将新类定义为元素或项,并为每个div添加一个类

CSS 

.elementItem
{
    //use height or min height
}

HTML

<div id="sheds" class="elementId">
    Content
</div>

参见JSFiddle:http://jsfiddle.net/dKfVL/

答案 7 :(得分:1)

首先检查我的解决方案:http://jsfiddle.net/dKfVL/4/

上述解决方案使用JavaScript,当点击链接时,它会向所需的div动态 增加高度。

var fixLink = $(".sub_navi li:last a"); // change this to a/c to your requirement

fixLink.click(function(){
    var targetDiv = fixLink.attr("href"); //get the ID of div to be fixed
    $(targetDiv).height($(window).height());
});  

之后没有删除高度,我没有看到你想要这样做的原因。但是如果你真的想这样做,你可以监视浏览器的滚动事件,如果滚动大于视口高度,那么你可以将目标div的高度设置为auto


选项2:
如果你不想使用javascript,你可以使用css的vh单位,这与css中的%单位非常相似,区别在于它相对于视口,而且它目前仅适用于 chrome

CSS

#med_vac {
  height: 100vh;
}

jsfiddle:http://jsfiddle.net/dKfVL/5/
注意:这不是跨浏览器

答案 8 :(得分:1)

尝试这个小提琴:http://jsfiddle.net/dKfVL/9/

我不确定单独使用css是否可行(至少不是跨浏览器)。

我已经使用jQuery来确保#med_vac元素有足够的高度来确保标题显示在页面顶部。我已经设置了在调整窗口大小时运行的代码,因此它也会响应任何屏幕大小的变化。

希望这有帮助!

答案 9 :(得分:1)

更好的一个(不需要填充div!)

尝试使用this jsfiddle。它非常适合我。

Highlights of this fiddle:

  1. 不需要填充div
  2. 仅在单击最后一个链接时更改最后一个包装div的高度
  3. 以下代码。

    $(document).ready(function(){
      //apply height change while clicking on last link only
      $("ul.sub_navi li a:last").click(function(){
        var $targ= $($(this).attr("href"));
        if($targ.height() < $(window).height()){
          $targ.css('min-height', $(window).height())
        }
      });
    });​
    

答案 10 :(得分:1)

如果您不介意重新组织的部分将点击的目标移到顶部,那么这可以正常工作http://jsfiddle.net/robx/dKfVL/34/

我做到了这一点,所选择的部分被放在第一个“牛”之下。不知道那是什么,但似乎它意味着保持原样。

我在这里看到的唯一可行选择是:     

          
  1. 隐藏所有内容并仅显示所点击的(手风琴或     标签式)。       
  2. 通过克隆重新组织,追加和删除以便     选定的部分向上移动并推动其余部分。       
  3. 放一些     在底部的丑陋的大边缘总是在那里(不受欢迎     对我来说。
  4.      希望这有助于指出你更好的方向。

答案 11 :(得分:1)

这是一个更加跨浏览器和无JavaScript的解决方案。

然而,这意味着你可以使用绝对定位,因此对浮点数不太友好,等等:

#med_vac {
    position: absolute;    
    height: 100%;
}

演示此解决方案的小提琴:

http://jsfiddle.net/fFL7x/