Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/461.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使命名锚书签在单击时始终显示在屏幕顶部_Javascript_Jquery_Html_Css - Fatal编程技术网

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

Javascript 使命名锚书签在单击时始终显示在屏幕顶部,javascript,jquery,html,css,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" a

我的标记如下:

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

    编辑


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

    您将希望用另一个
    div
    包装导航,以便将CSS应用于整个导航。完成后,您可以将收割台定位到固定位置。下一步是通过将页面内容向下移动一些(导航高度)来为页面顶部的固定标题腾出空间,这样做可以将所有内容包装在另一个
    分区中(不包括此内容分区中的导航),并应用一些CSS-
    边距顶部:(导航高度)

    编辑:

    啊,好吧,我知道你想要什么了。要实现这一点,您可以设置
    div
    的高度,或者在所有俯冲上使用
    min height
    ,这样当您转到锚点时,它们将在底部留出空间供浏览器向下滚动

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

    CSS 
    
    .elementItem
    {
        //use height or min height
    }
    
    HTML
    
    <div id="sheds" class="elementId">
        Content
    </div>
    
    CSS
    .elementItem
    {
    //使用高度或最小高度
    }
    HTML
    内容
    
    参见JSFIDLE:

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

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

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

    参见小提琴:
    首先查看我的解决方案:

    上面的解决方案使用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:
    注意:这不是跨浏览器的

    试试这把小提琴:

    我不确定单独使用css就可以做到这一点(至少不需要跨浏览器)

    我使用jQuery确保#med#u vac元素具有足够的高度,以确保标题显示在页面顶部。我已经将代码设置为在调整窗口大小时运行,因此它也将响应任何屏幕大小的更改

    希望这有帮助

    将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)
      });
    });​
    

    解决方案:

    将此添加到您的代码中:

    <!-- 
      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>
    
    
    $(文档).ready(函数(){
    $(“a”)。单击(函数(){
    var targ=$(this.attr('href');
    变量元素=$(targ);
    document.location.href=target;
    阿托普(elem);
    document.location.href=target;
    });
    });
    函数组(inObj){
    变量y=$(inObj).height();
    var z=$(“#lowerPadding”).height();
    var w=$(window.height();
    而(y+z);
    z=$(“#lowerPadding”).height();
    }
    }
    
    • 单击
      元素,转到位置
    • 获取目标位置、填充标记和窗口的高度

    • 标记添加到填充标记,直到目标位置位于窗口顶部

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


    我解决您问题的初始解决方案与上面的@saurabh类似:

    你可以考虑的其他东西,如果你最终使用jQuery,则突出焦点内容——同时对其余部分进行调暗…

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

    试试看。这对我来说非常有效

    这把小提琴的亮点:

  • 不需要填充div
  • 仅在单击最后一个链接时更改最后一个包装器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())
        }
      });
    });​
    
    $(文档).ready(函数(){
    //仅在单击最后一个链接时应用高度更改
    $(“ul.sub_navi li a:last”)。单击(函数(){
    var$targ=$($(this.attr(“href”));
    如果($target.height()<$(window.height()){
    $target.css('min-height',$(window.height())
    }
    });
    });​
    
    如果您不
    $('.sub_navi a').click(function() {
        var theID = $(this).attr('href');
        $(theID+':last-child').css('min-height', $(window).height());
    })
    
    $('.sub_navi a').click(function() {
        $('#content div').css('opacity',0.5);
        var theID = $(this).attr('href');
        $(theID).css('opacity', 1);
    })
    
    $(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())
        }
      });
    });​
    
    #med_vac {
        position: absolute;    
        height: 100%;
    }
    
    <!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>