5

我的标记如下:

<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,如果是,什么代码?

编辑

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

4

12 回答 12

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)
  });
});​
于 2012-09-07T14:03:45.123 回答
2

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

假设这意味着您要隐藏页面上的所有部分,只显示与单击的链接对应的部分,您要查找的内容称为 Accordian,您可以在此处找到示例。

于 2012-09-02T17:27:02.673 回答
2

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

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

于 2012-09-02T18:05:31.563 回答
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 更容易并且跨浏览器。

于 2012-09-08T21:26:16.607 回答
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);
})

​</p>

于 2012-09-10T14:51:30.007 回答
2

这是我所做的:

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

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

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

在这里在线测试: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 测试。

于 2012-09-11T15:38:46.603 回答
1

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

#topnav
{
    position: fixed;
}

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

编辑:

啊,好吧,我知道你想要什么。div要做到这一点,您可以设置's的高度,或者min-height在您到达锚点时使用所有的潜水方式,它们将在底部留出空间供浏览器向下滚动到。

所以你必须在你的 CSS 中定义一个新类作为元素或项目,并为每个div's添加一个类

CSS 

.elementItem
{
    //use height or min height
}

HTML

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

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

于 2012-09-02T17:26:54.090 回答
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.


方案二:
如果不想使用javascript,可以使用css的vhunit,和css中的unit很相似%,不同的是它是相对于视口的,目前只支持chrome

CSS

#med_vac {
  height: 100vh;
}

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

于 2012-09-05T10:01:45.057 回答
1

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

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

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

希望这可以帮助!

于 2012-09-05T13:22:38.423 回答
1

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

试试这个 jsfiddle。它对我来说完美无缺。

Highlights of this fiddle:

  1. 不需要填充 div
  2. 仅在单击最后一个链接时更改最后一个包装器 div 的高度

代码如下。

$(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())
    }
  });
});​
于 2012-09-10T16:12:59.113 回答
1

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

我这样做是为了将所选部分放在第一个“牛”的正下方。不知道那是什么,但似乎它应该留在原地。

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

  1. 将它们全部隐藏并仅显示单击的(手风琴或标签样式)。
  2. 通过克隆、附加和删除重新组织,以便选定的部分向上移动并向下推其余部分。
  3. 在底部放置一些丑陋的大边距,它总是在那里(对我来说不受欢迎)。
希望这有助于为您指明更好的方向。

于 2012-09-11T04:19:57.313 回答
1

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

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

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

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

http://jsfiddle.net/fFL7x/

于 2012-09-11T08:18:01.727 回答