什么是最简单的jQuery方法有一个“位置:固定”(总是在顶部)div? [英] What is the simplest jQuery way to have a 'position:fixed' (always at top) div?

查看:155
本文介绍了什么是最简单的jQuery方法有一个“位置:固定”(总是在顶部)div?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对jQuery比较新,但到目前为止,我看到我喜欢。我想要的是一个div(或任何元素)在页面的顶部,就像position:fixed在每个浏览器中工作。

I'm relatively new to jQuery, but so far what I've seen I like. What I want is for a div (or any element) to be across the top of the page as if "position: fixed" worked in every browser.

想要复杂的东西。我不想要巨大的CSS黑客。我更喜欢如果只使用jQuery(版本1.2.6)是足够好,但如果我需要jQuery-UI-core,那也很好。

I do not want something complicated. I do not want giant CSS hacks. I would prefer if just using jQuery (version 1.2.6) is good enough, but if I need jQuery-UI-core, then that's fine too.

尝试$(#topBar)。scrollFollow();

I've tried $("#topBar").scrollFollow(); <-- but that goes slow... I want something to appear really fixed.

推荐答案

使用此HTML:

<div id="myElement" style="position: absolute">This stays at the top</div>

这是您要使用的javascript。它将事件附加到窗口的滚动,并将元素向下移动到您滚动的位置。

This is the javascript you want to use. It attaches an event to the window's scroll and moves the element down as far as you've scrolled.

$(window).scroll(function() {
    $('#myElement').css('top', $(this).scrollTop() + "px");
});






正如下面的注释所指出的,推荐将事件附加到滚动事件 - 当用户滚动时,它触发A LOT,并可能导致性能问题。考虑使用Ben Alman的 debounce / throttle 插件来减少开销。

这篇关于什么是最简单的jQuery方法有一个“位置:固定”(总是在顶部)div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆