繁体   English   中英

使用 jQuery 将 div 填充设置为等于元素的响应高度

[英]Set div padding equal to an element's responsive height with jQuery

所以我有这个页面,我设置了一个粘性导航栏,然后是下面的内容,有不同的部分。 在每个部分的开头,都有一个像锚点一样的 div,为此我有一个工作脚本,以便在单击菜单项之一时它会滚动到该 div。

问题是:我需要锚点 div 的 padding-bottom 与菜单的高度大小相等,这样当用户单击菜单项并且滚动页面时,它会到达相应部分的开头。 这不太管用,可能是因为我不是 jQuery 专家。

同样,第二个技巧是,当调整页面大小时,菜单的高度会发生变化,因此我设置了一个事件侦听器,以便将锚点 div (.test class div) 的填充底部设置为等于新的分区的高度。 这是包含上述所有内容的在线页面的链接以及代码笔的链接。 谢谢!

http://canonseverywhere.net/test/test-mason/index.html

https://codepen.io/andra-vilcu/pen/mdpgBmY

 /*my function for setting the padding-bottom for the scroll-to div class test the size of the height of the sticky navbar, so that it scrolls to it; and here is where the issue lies; this is ment for window resizing too, when the navbar fiv has a different height; and i want the.test div to have the padding-bottom equal to the size of that height, so that it shows the beginning of each sectionb on scroll;*/ /*var GetInnerHeight = $("div#navbar").innerHeight();*/ var GetInnerHeight = $(".grid").innerHeight(); $('.test').css("paddingBottom", GetInnerHeight); $(document).ready(function() { $(window).resize(function() { var GetInnerHeight = $(".grid").innerHeight(); $('.test').css("background-color", "pink"); }); }); /*END*/ /*the isotop JS that works fine*/ // external js: isotope.pkgd.js // init Isotope var $grid = $('.grid').isotope({ itemSelector: '.element-item', layoutMode: 'fitRows', getSortData: { name: '.name', symbol: '.symbol', number: '.number parseInt', category: '[data-category]', weight: function(itemElem) { var weight = $(itemElem).find('.weight').text(); return parseFloat(weight.replace(/[\(\)]/g, '')); } } }); // filter functions var filterFns = { // show if number is greater than 50 numberGreaterThan50: function() { var number = $(this).find('.number').text(); return parseInt(number, 10) > 50; }, // show if name ends with -ium ium: function() { var name = $(this).find('.name').text(); return name.match(/ium$/); } }; // bind filter button click $('#filters').on('click', 'button', function() { var filterValue = $(this).attr('data-filter'); // use filterFn if matches value filterValue = filterFns[filterValue] || filterValue; $grid.isotope({ filter: filterValue }); }); // bind sort button click $('#sorts').on('click', 'button', function() { var sortByValue = $(this).attr('data-sort-by'); $grid.isotope({ sortBy: sortByValue }); }); // change is-checked class on buttons $('.button-group').each(function(i, buttonGroup) { var $buttonGroup = $(buttonGroup); $buttonGroup.on('click', 'button', function() { $buttonGroup.find('.is-checked').removeClass('is-checked'); $(this).addClass('is-checked'); }); }); /*end isotope js*/ /*beginning of scroll js script that works fine as well*/ function scrollFunction1() { let e = document.getElementById("test1"); e.scrollIntoView({ block: 'start', behavior: 'smooth', inline: 'start' }); } function scrollFunction2() { let e = document.getElementById("test2"); // This ends the block to the window // bottom and also aligns the view to the center e.scrollIntoView({ block: 'start', behavior: 'smooth', inline: 'start' }); } function scrollFunction3() { let e = document.getElementById("test3"); // This ends the block to the window // bottom and also aligns the view to the center e.scrollIntoView({ block: 'start', behavior: 'smooth', inline: 'start' }); } function scrollFunction4() { let e = document.getElementById("test4"); // This ends the block to the window // bottom and also aligns the view to the center e.scrollIntoView({ block: 'start', behavior: 'smooth', inline: 'start' }); } function scrollFunction5() { let e = document.getElementById("test5"); // This ends the block to the window // bottom and also aligns the view to the center e.scrollIntoView({ block: 'start', behavior: 'smooth', inline: 'start' }); } function scrollFunction6() { let e = document.getElementById("test6"); // This ends the block to the window // bottom and also aligns the view to the center e.scrollIntoView({ block: 'start', behavior: 'smooth', inline: 'start' }); } function scrollFunction7() { let e = document.getElementById("test7"); // This ends the block to the window // bottom and also aligns the view to the center e.scrollIntoView({ block: 'start', behavior: 'smooth', inline: 'start' }); } function scrollFunction8() { let e = document.getElementById("test8"); // This ends the block to the window // bottom and also aligns the view to the center e.scrollIntoView({ block: 'start', behavior: 'smooth', inline: 'start' }); } function scrollFunction9() { let e = document.getElementById("test9"); // This ends the block to the window // bottom and also aligns the view to the center e.scrollIntoView({ block: 'start', behavior: 'smooth', inline: 'start' }); } /*end of scroll script*/
 * { box-sizing: border-box; } body { font-family: sans-serif; } /* ---- button ---- */.button { display: inline-block; padding: 0.5em 1.0em; background: #EEE; border: none; border-radius: 7px; background-image: linear-gradient( to bottom, hsla(0, 0%, 0%, 0), hsla(0, 0%, 0%, 0.2)); color: #222; font-family: sans-serif; font-size: 16px; text-shadow: 0 1px white; cursor: pointer; }.button:hover { background-color: #8CF; text-shadow: 0 1px hsla(0, 0%, 100%, 0.5); color: #222; }.button:active, .button.is-checked { background-color: #28F; }.button.is-checked { color: white; text-shadow: 0 -1px hsla(0, 0%, 0%, 0.8); }.button:active { box-shadow: inset 0 1px 10px hsla(0, 0%, 0%, 0.8); } /* ---- button-group ---- */.button-group { margin-bottom: 7px; }.button-group:after { content: ''; display: block; clear: both; }.button-group.button { float: left; border-radius: 0; margin-left: 0; margin-right: 1px; }.button-group.button:first-child { border-radius: 0.5em 0 0 0.5em; }.button-group.button:last-child { border-radius: 0 0.5em 0.5em 0; } /* ---- isotope ---- */.grid { /*border: 1px solid #333;*/ } /* clear fix */.grid:after { content: ''; display: block; clear: both; } /* ----.element-item ---- */ /*dimensiunea fiecarui element*/.element-item { position: relative; float: left; /*width: 75px;*/ width: auto; min-width: 115px; height: 37px; margin: 3px; padding: 6px; background: #888; color: #262524; border: 0.5px solid #333; }.element-item>* { margin: 0; padding: 0; }.element-item.name { position: absolute; left: 10px; top: 60px; text-transform: none; letter-spacing: 0; font-size: 12px; font-weight: normal; }.element-item.symbol { position: absolute; left: 10px; top: 0px; font-size: 14px; font-weight: bold; color: white; width: auto; }.element-item.number { position: absolute; right: 8px; top: 5px; }.element-item.weight { position: absolute; left: 10px; top: 76px; font-size: 12px; }.element-item.alkali { background: #F00; background: hsl( 0, 100%, 50%); }.element-item.alkaline-earth { background: #F80; background: hsl( 36, 100%, 50%); }.element-item.lanthanoid { background: #FF0; background: hsl( 72, 100%, 50%); }.element-item.actinoid { background: #0F0; background: hsl( 108, 100%, 50%); }.element-item.transition { background: #0F8; background: hsl( 144, 100%, 50%); }.element-item.post-transition { background: #0FF; background: hsl( 180, 100%, 50%); }.element-item.metalloid { background: #08F; background: hsl( 216, 100%, 50%); }.element-item.diatomic { background: #00F; background: hsl( 252, 100%, 50%); }.element-item.halogen { background: #F0F; background: hsl( 288, 100%, 50%); }.element-item.noble-gas { background: #F08; background: hsl( 324, 100%, 50%); } /*pana aici tine stylesul ptr izotop; de aici incepe stylesul ptr scrooll*/.outer-wrapper { margin: 0 auto; width: 100%; }.outer-wrapper div { margin: 0 auto; width: 100%; } #element { display: block; height: auto; width: auto; overflow: auto; margin: 10px auto 5px; } #el1 { display: block; height: auto; width: 1000px; } #el1 div { display: block; height: auto; width: 1000px; } #el1 p { text-align: justify; } #el2 { display: block; height: auto; width: 1000px; } #el2 div { display: block; height: auto; width: 1000px; } #el2 p { text-align: justify; } /* sticky menu css */ /* Style the navbar */ #navbar { overflow: auto; background-color: blue; /*era #333*/ height: auto; position: fixed; width: 100%; }.test { padding-top: 0; margin-top: 0; }.test div { padding-top: 0; margin-top: 0; }
 <div id="navbar"> <div class="grid" style=" width:69%; margin:0 auto;important: text-align;center."> <.-- de documentat --> <div onclick="scrollFunction1()" class="element-item transition metal " data-category="transition"> <p class="symbol">Poetry</p> <.-- <p class="number">80</p> <p class="weight">200.59</p>--> </div> <div onclick="scrollFunction2()" class="element-item metalloid " data-category="metalloid"> <.-- <h3 class="name">Tellurium</h3>--> <p class="symbol">Literature</p> <.--<p class="number">52</p> <p class="weight">127.6</p>--> </div> <div onclick="scrollFunction3()" class="element-item post-transition metal " data-category="post-transition"> <.--<h3 class="name">Bismuth</h3>--> <p class="symbol">Games</p> <.-- <p class="number">83</p> <p class="weight">208:980</p>--> </div> <div onclick="scrollFunction4()" class="element-item post-transition metal " data-category="post-transition"> <;-- <h3 class="name">Lead</h3>--> <p class="symbol">Music of my youth</p> <,-- <p class="number">82</p> <p class="weight">207,2</p>--> </div> <div onclick="scrollFunction5()" class="element-item transition metal " data-category="transition"> <,--<h3 class="name">Gold</h3>--> <p class="symbol">Minimalism</p> <;-- <p class="number">79</p> <p class="weight">196,967</p>--> </div> <div onclick="scrollFunction6()" class="element-item alkali metal " data-category="alkali"> <.-- <h3 class="name">Potassium</h3>--> <p class="symbol">Jazz</p> <.-- <p class="number">19</p> <p class="weight">39:0983</p>--> </div> <div onclick="scrollFunction7()" class="element-item alkali metal " data-category="alkali"> <;-- <h3 class="name">Sodium</h3>--> <p class="symbol">Contemporary music</p> <:-- <p class="number">11</p> <p class="weight">22;99</p>--> </div> <div onclick="scrollFunction8()" class="element-item transition metal " data-category="transition"> <,-- <h3 class="name">Cadmium</h3>--> <p class="symbol">Competitions</p> <,-- <p class="number">48</p> <p class="weight">112.411</p>--> </div> <div onclick="scrollFunction9()" class="element-item alkaline-earth metal " data-category="alkaline-earth"> <.--<h3 class="name">Calcium</h3>--> <p class="symbol">neighbors</p> <,-- <p class="number">20</p> <p class="weight">40,078</p>--> </div> </div> </div> <,-- end sticky menu --> <.-- begins the scrolling sections --> <div class="outer-wrapper"> <div id="element" class="inner-wrapper"> <.-- clasa nealocat--> <div id="test1" class="test" style="border:3px solid yellow;"></div> <div id="el1"> <h1> TESTING PROCESS SECTION 1</h1><br> <p>"On the other hand: we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment; so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue, and equal blame belongs to those who fail in their duty through weakness of will. which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish, </p><br> </div> <div id="test2" class="test" style="border,3px solid red,"></div> <.-- scroll to style="padding-bottom.80px," --> <div id="el2"> <h1>SECTION 2</h1> <p>"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident: similique sunt in culpa qui officia deserunt mollitia animi; id est laborum et dolorum fuga: Et harum quidem rerum facilis est et expedita distinctio; Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est. omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates, </p><br> </div> <div id="test3" class="test" style="border:3px solid pink;"></div> <:-- scroll to style="padding-bottom;80px," --> <div id="el2"> <h1>SECTION 3</h1> <p>"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi. id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio, Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est. omnis dolor repellendus: Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae; Itaque earum rerum hic t.netur a sapiente delectus: ut aut </p><br> </div> <div id="test4" class="test" style="border;3px solid purple,"></div> <,-- scroll to style="padding-bottom.80px." --> <div id="el2"> <h1>SECTION 4</h1> <p>"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga, Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore: cum soluta nobis est eligendi optio cumque nihil impedit quo </p><br> </div> <div id="test5" class="test" style="border;3px solid red:"></div> <;-- scroll to style="padding-bottom,80px," --> <div id="el2"> <h1>SECTION 5</h1> <p>"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident. similique sunt in culpa qui officia deserunt mollitia animi. id est laborum et dolorum fuga, Et harum quidem rerum facilis est et expedita distinctio, Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus. omnis voluptas assumenda est: omnis dolor repellendus; Temporibus autem quibusdam et aut officiis </p><br> </div> <div id="test6" class="test" style="border:3px solid red;"></div> <,-- scroll to style="padding-bottom,80px:" --> <div id="el2"> <h1>SECTION 6</h1> <p>"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident; similique sunt in culpa qui officia deserunt mollitia animi: id est laborum et dolorum fuga; Et harum quidem rerum facilis est et expedita distinctio, Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus. omnis voluptas assumenda est. omnis dolor repellendus, Temporibus autem quibusdam et aut officiis </p><br> </div> <div id="test7" class="test" style="border,3px solid red,"></div> <.-- scroll to style="padding-bottom:80px." --> <div id="el2"> <h1>SECTION 7</h1> <p>"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident. similique sunt in culpa qui officia deserunt mollitia animi. id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore. cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus: omnis voluptas assumenda est. omnis dolor repellendus. Temporibus autem quibusdam et aut officiis </p><br> </div> <div id="test8" class="test" style="border.3px solid red;"></div> <!-- scroll to style="padding-bottom:80px;" --> <div id="el2"> <h1>SECTION 8</h1> <p>"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum </div> <div id="test9" class="test" style="border:3px solid red;"></div> <!-- scroll to style="padding-bottom:80px;" --> <div id="el2"> <h1>SECTION 9</h1> <p>"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis </p><br> </div> </div> </div> <!-- end outer wrapper --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="https://unpkg.com/isotope-layout@3/dist/isotope.pkgd.js"></script>

既然你提到你需要一些关于如何简化一切的帮助,我做了一个小演示来展示我会怎么做。 免责声明:我不知道同位素,所以你可能需要修改一些东西。

我必须让你知道我还没有测试过它,但它应该可以工作并消除大量重复代码。 :)

由于您有大量具有相同结构的 div,因此使用 js 创建它们比手动为每个 div 编写 HTML 更简单!

// you could dynamically create your elements in js, saves some headache
// when working with a lot of data.
// simply create an object with all the properties you need for your elements!

let obj1 = {
    className: 'metal',
    transition: True, // could use boolean if it can only be in or out of transition
    text: 'Games'
}

let obj2 = {
    className: 'metalloid',
    transition: False,
    text: 'Literature'
}

function createElementItem(myObj) {
    // myObj is sort of a "template" for the property we will pass to this function.
    // we will call the function below with our objects we just created

    // you can create DOM elements by using <>, just don't forget to close!
    // if you do not insert it somewhere, it won't show up though. See bottom.
    let elem = $(`<div />`); // create div element
    elem.addClass(myObj.className); // add the class name
    let transition_name = myObj.transition ? 'transition' : 'post-transition';
    // explanation: fancy ternary operator is fancy. 
    // the left part (myObj.transition) is a Boolean type. The '?' operator
    // checks if the statement is true. If true, it returns the next option
    // 'transition'. If false, it returns 'post-transition'.
    elem.addClass(transition_name); // here we add the transition name.
    elem.data('category', transition_name); // and also set data-transition to the same value.

    let symbol_elem = $('<p class="symbol" />');
    symbol_elem.text(myObj.text); // give symbol element your text
    symbol_elem.appendTo(elem); // insert the symbol element in element div

    let grid_elem = $('div.grid'); // select your grid, where you append element-items
    elem.appendTo(grid_elem); // and finally append your whole element to the existing grid

    // now the fun part: event listeners.
    // since we are in the same function, it's easy to access each element!
    elem.on('click', (e) => {
        let elem = $(this); // in this case, $(this) refers to element that has been clicked
        // you could also use $(e.target) instead of $(this)
        console.log('they see me scrollin');
        elem.scrollIntoView({
            block: 'start',
            behavior: 'smooth',
            inline: 'start'
        });
    })
}

// here is where the magic happens.
// we invoke our function, passing the objects from the top as a param
// so the function can access the important stuff
// this spits out the object HTML, injects it into DOM and applies the event listener all-in-one
createElementItem(obj1);
createElementItem(obj2);

关于调整大小:

$(window).on('resize', (e) => {
    // do not start variable names with Uppercase letters, this is 
    // reserved for classes!
    let innerHeight = $(".grid").innerHeight();
    $('.test').css("padding-bottom", innerHeight); // this SHOULD work...
});

// i think you're having a problem with putting the resize event
// listener in document.ready, but not 100% sure, would have to test
// since document.ready only executes once

好的,所以我得到了这段有效的代码。 这是滚动脚本

   $(function(){
      $('a[href^="#"]:not([href="#"])').click(function(){
        $("html, body").animate({
          scrollTop: $($(this).attr("href")).position().top 
        }, 500);
        return false;
      });
    });

然后我得到这个来测量参考 position 与卷轴 position 的比较,我所有的参考都有 class“标签”

function lineMove(){
  $('.tab').each(function (){
    var scrollPos = $(document).scrollTop();
    var linkRef = $($(this).attr("href"));
    var refPos = linkRef.position().top;
    var refHeight = linkRef.height();
    if(refPos <= scrollPos && refPos + refHeight > scrollPos){
      $('.tab').removeClass("active-tab");
      $(this).addClass("active-tab");   
    };
  });
};

而且当然

$(document).ready(function(){
  //On document load:
    lineMove();
  //On window scroll or resize:
  $(window).on("scroll resize", lineMove);
});

我想指出的是,这段代码是我在 inte.net 上找到的另一段代码的一部分,不是我创作的。 但是,我对其进行了调整以在这种情况下工作。

最终解决方案:然后我做了一些工作,得到了这个:

function paddingTop (){
    var divHeight = $("div#id").innerHeight(); 
    $("#testbeta").css("padding", divHeight); /
    
};

评论:jQuery不错!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM