2

div上にあり、下にスクロールすると常に表示されるJavascript(またはプログラムでCSS)を使用して単純なフローティングを構築する正しい方法は何ですか?

今、私はこのような例を見てきまし。下にスクロールすると、divがジャンプして遅延が発生します。ページのコンテンツが自分のものでない場合は、常に一番上に表示したいのですが
、スクリプトはクロム拡張を介して挿入されます

それはできますか?このようなもの ; ただし、それほど複雑ではなく、ページのコンテンツに依存しません

4

2 に答える 2

4

保持したい要素のclassorを使用して、いくつかのCSSルールを適用する必要があります。id

たとえば、要素クラスが.topnavigation

jQueryで次のことができます

<style>
.topnavigation {
    width:;/* add the width here */
    position:static;
}
.topnavigation.scrolling {
    position:fixed;
    top:0px;
}
</style>
<script>
$(window).scroll(function () { 
    if($(this).scrollTop() > 50) // change 50 to what you want (work out how far the nav is from the top of the page alraedy and add it there, that'll make it smoother transition)
    {
        $('.topnavigation').addClass('scrolling');
    } else {
        $('.topnavigation').removeClass('scrolling');
    }
});
</script>

jQueryを使用できない場合は、通常のjavascriptで次のことを行うことができます。

更新日:2017年1月6日 document.querySelectorメソッドとElement.classListメソッドを使用するようにこれを更新しました。最新のブラウザとIE10はすべて、これらの方法をサポートしています。

window.addEventListener('scroll',checkPosition,false);
function checkPosition()
{
    // #theid or #theclass or standard element selector
    var xNAV = document.querySelector("#topnav"); 
    if(window.scrollY > 50)
    {
        xNAV.classList.add("scrolling");
    } else {
        xNAV.classList.remove("scrolling");
    }
}
于 2012-11-12T09:33:24.557 に答える
0

JavaScriptを使用して、フローティングにするタイミングを決定し、cssを追加します。position:fixed

于 2012-11-12T09:11:02.440 に答える