div
上にあり、下にスクロールすると常に表示されるJavascript(またはプログラムでCSS)を使用して単純なフローティングを構築する正しい方法は何ですか?
今、私はこのような例を見てきました。下にスクロールすると、divがジャンプして遅延が発生します。ページのコンテンツが自分のものでない場合は、常に一番上に表示したいのですが
、スクリプトはクロム拡張を介して挿入されます
それはできますか?このようなもの ; ただし、それほど複雑ではなく、ページのコンテンツに依存しません
保持したい要素のclass
orを使用して、いくつかの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");
}
}
JavaScriptを使用して、フローティングにするタイミングを決定し、cssを追加します。position:fixed