wordpress での各ブログ投稿の後に、特別な DIV コンテンツ ボックスがあります。
ユーザーがブログ投稿を下にスクロールした後、設定された 1 秒の遅延後にのみ表示されるようにする方法を見つけたいと思います。
javascriptまたはjqueryでそれを行う方法はありますか?
以下のコードを試してください。このjsfiddleでテストできます
$("#div1").hide();
var windowHeight = $(window).height();
//alert(windowHeight);
var divHeight = $("#div0").height();
//var alert(divHeight);
var divBottomPos = $("#div0").offset().top + divHeight; //alert(divBottomPos);
var divIsShowing = false;
$(document).scroll(function () {
var scrollPos = $(this).scrollTop();
var bottomPageScrollPos = scrollPos + windowHeight;
//alert(bottomPageScrollPos);
if ((bottomPageScrollPos > divBottomPos) && (!divIsShowing)) {
$("#div1").delay(1000).show(0);
divIsShowing = true;
} else if ((bottomPageScrollPos < divBottomPos) && (divIsShowing)) {
$("#div1").hide();
divIsShowing = false;
}
});
すべてのブログ投稿にブログ投稿のクラスがあると仮定します。それぞれにのスタイルを追加しますdisplay:none
。次に、これはそれを実現するコードです。
$(function(){
var $blogs = $('.blogpost');
$(window).scroll(function(){
var windowTop = $(window).scrollTop();
var windowBottom = windowTop + $(window).height();
$blogs.each(function(){
var elemTop = $(this).offset().top;
var elemBottom = elemTop + $(this).height();
if(windowBottom > elemBottom){
setTimeout(function(){
$(this).show();
}, 1000);
}
}
}
});
もちろん。を使用setTimeout
して、遅延後にアクションを実行 (関数を呼び出す) したりscroll
、要素 (ドキュメント全体を含む) のイベントを jQuery のon
関数 (またはそのショートカットscroll
) を使用して非常に簡単にフックしたりできます。したがって、これらの組み合わせを使用してdiv
(jQuery を介してshow
) 表示させることができます。たとえば、次のようになります。
// At the end of your page, just before the closing </body> tag
(function($) {
var timer;
// Set up the timer and scroll event handler
timer = setTimeout(showDiv, 2000); // 2000 = two seconds
$(document.body).on('scroll', handleScroll);
// Show the div, and cancel the scroll event handler or timer
function showDiv() {
clearTimeout(timer);
$(document.body).off('scroll', handleScroll);
}
// Handle the scroll event
function handleScroll() {
// Check to see if the body has scrolled up past the top of the article
if ($(this).scrollTop() > $("#thearticle").offset().top) {
showDiv();
}
}
})(jQuery);
明らかにそれは単なる概念ですが、正しい方向に進むはずです。
SOの別のページから、これが機能することがわかりました。
しかし、スクロールトップ機能の200ピクセル上でアクティブにする方法があるかどうか疑問に思っています。
現在、ユーザーが最初の DIV の絶対開始点までスクロールするとアクティブになりますが、ユーザーが DIV の一番下に来たときにアクティブにできるようにしたいと考えています。
$(document).ready( function() {
$("#dvid").hide(); //hide your div initially
var topOfOthDiv = $("#othdiv").offset().top;
$(window).scroll(function() {
if($(window).scrollTop() > topOfOthDiv) { //scrolled past the other div?
$("#dvid").show(); //reached the desired point -- show div
}
});
});