此jQuery代码片段可将元素保留在页面滚动时。 演示显示了对右侧侧边栏AD的影响。 该代码既作为独立脚本,又是可重复使用的jQuery插件。 最后,一个常见问题解答解决了常见的jquery滚动问题。
>代码(独立):
//keep element in view (function($) { $(document).ready(function() { var elementPosTop = $('#jq4u-sidebar-ads').position().top; $(window).scroll(function() { var wintop = $(window).scrollTop(), docheight = $(document).height(), winheight = $(window).height(); if (wintop > elementPosTop) { $('#jq4u-sidebar-ads').css({ "position": "fixed", "top": "10px" }); } else { $('#jq4u-sidebar-ads').css({ "position": "inherit" }); } }); }); })(jQuery);
代码(jQuery插件):
/** * jQuery keep element in view plugin. * * @author Sam Deering * @copyright Copyright (c) 2012 jQuery4u * @license http://jquery4u.com/license/ * @link http://jquery4u.com * @since Version 1.0 * @notes Plugin only works on scroll down elements. */ (function($) { $.fn.keepElementInView = function() { var elemPosTop = this.position().top; $(window).scroll(function() { var wintop = $(window).scrollTop(), docheight = $(document).height(), winheight = $(window).height(); if (wintop > elemPosTop) { this.css({ "position": "fixed", "top": "10px" }); } else { this.css({ "position": "inherit" }); } }); return this; }; $(document).ready(function() { $('#jq4u-sidebar-ads').keepElementInView(); }); })(jQuery);
> >本节提供了有关jQuery元素视图滚动滚动的常见问题的简洁答案,包括用于动画和即时滚动的技术,水平滚动,视口检查以及按钮触发的滚动。 代码示例稍微重新格式化以提高可读性。
Q1:动画滚动到元素?>
$('html, body').animate({ scrollTop: $("#elementID").offset().top }, 2000);
$('html, body').scrollTop($("#elementID").offset().top);
>
$('html, body').animate({ scrollLeft: $("#elementID").offset().left }, 2000);
Q5:滚动到按钮单击按钮?
function isInViewport(element) { let elementTop = $(element).offset().top; let elementBottom = elementTop + $(element).outerHeight(); let viewportTop = $(window).scrollTop(); let viewportBottom = viewportTop + $(window).height(); return elementBottom > viewportTop && elementTop < viewportBottom; }
以上是jQuery在滚动时查看元素的详细内容。更多信息请关注PHP中文网其他相关文章!