javascript - 计算pinboard风格博客的容器高度(基于绝对元素)

标签 javascript jquery html css

我正在使用 tutorial by Ben Holland 开发一个钉板风格的博客(如 Pinterest) .每个图钉都有一个绝对位置,它的位置(顶部和左侧)是用 jQuery 脚本计算的 http://labs.benholland.me/pinterest/js/script-centered.js

一切正常(see demo),但唯一需要做的就是添加页脚。当我尝试添加页脚时(无论它如何定位:相对或绝对),它要么显示在页面顶部 (position:relative),要么漂浮在页面中间的某个位置页面(position:absolute;bottom:0)。页脚从不显示在博客下方。

我尝试了很多 CSS 解决方案(clearfixes、floats、各种不同的位置组合),毕竟我得出的结论是没有 JS 是不可能的。

问题可以通过将看板放在容器中,给容器position:relative并添加正确的高度来解决。在此之后,页脚可以放在容器下面。这就是我被困的地方。

我是 JavaScript 的初学者,有人可以帮助我吗?

最佳答案

就像你说的,你可以用一个div来包含这些绝对元素 结构如下:

<body onload="setupBlocks();">
    <header>header</header>
    <section id="container">
        <div class="block">
            <p>Lorem ipsum dolor sit amet....</p>
        </div>
        ......
    </section>
    <footer>footer</footer>
</body>

和 CSS 代码如下:

header{height:30px;background-color:green;}
footer{height:20px;background-color:gray;}
section{position:relative;} //It's important,absolute element will calculate position depending on nearest parent which has sure position.

关于js代码,请看array:block[],这个数组记录了每一列的高度,你可以在console中打印出来。 所以你需要做的只是将 block[] 的最大值设置为 section。 在这里,我在函数 positionBlocks 中添加了两行,并添加了一个获取最大值的函数

function positionBlocks() {
$('.block').each(function(i){
    var min = Array.min(blocks);
    var index = $.inArray(min, blocks);
    var leftPos = margin+(index*(colWidth+margin));
    $(this).css({
        'left':(leftPos+spaceLeft)+'px',
        'top':min+'px'
    });
    blocks[index] = min+$(this).outerHeight()+margin;
}); 
var max = Array.max(blocks);    //you need to write a function to get max value of block
$('section').height(max);       //set section(or div,as you wish)'s height
}

// Function to get the Min value in Array
Array.min = function(array) {
    return Math.min.apply(Math, array);
};

// Function to get the Max value in Array
Array.max = function(array) {
    return Math.max.apply(Math, array);
};

如果section的高度太小,想让脚到底,需要计算(scollheight-other's height)、与section的高度比较,替换到设置的seciton的高度线中。

关于javascript - 计算pinboard风格博客的容器高度(基于绝对元素),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24987001/

相关文章:

javascript - 如何使用 APEX_APPLICATION.G_F10(1) 函数的值在动态操作中设置条件确认操作

javascript - 当我想使用外部 "_this is undefined"关键字时出现 "this"错误

javascript - 为什么 JQuery 不传递替换 div 中的 post_id 和 post_type

ajax - Json 无法在 Django 中使用 Ajax 工作

javascript - 如何将附加元素最后放入容器中?

javascript - 如何从输入组件中获取值(学习目的)?

javascript - nodejs与node冲突(重新安装nodejs)

javascript - 如何使用JQuery/JS动态获取表单选项文本

javascript - Struts2上传多个文件前如何显示选中的文件名?

javascript - canPlayType 背后的基本原理是什么?