jQuery Simple Implementation of Floating Effect when Page Elements Set Top Example

  • 2021-07-06 10:08:08
  • OfStack

In this paper, an example is given to describe the method of jQuery to simply realize the suspension effect when the page elements are set to the top. Share it for your reference, as follows:

1. JS Code:


<script type="text/javascript">
  $.fn.smartFloat = function () {
    var position = function (element) {
      var top = element.position().top, pos = element.css("position");
      $(window).scroll(function () {
        var scrolls = $(this).scrollTop();
        if (scrolls > top) {
          if (window.XMLHttpRequest) {
            element.css({
              position: "fixed",
              top: 0
            });
          } else {
            element.css({
              top: scrolls
            });
          }
        } else {
          element.css({
            position: pos,
            top: top
          });
        }
      });
    };
    return $(this).each(function () {
      position($(this));
    });
  };
  // Binding 
  $("#float").smartFloat();
</script>

2. Html Code:


<div class="float" id="float" style="border: 1px solid #e0e0e0; padding: 10px;">
   I am the floating area when I set the top </div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />

For more readers interested in jQuery related content, please check the topics of this site: "Summary of Common Plugins and Usage of jQuery", "Summary of Common Classic Special Effects of jQuery", "Summary of Operation Skills of jQuery form", "Summary of Data Skills of Operation of json of jQuery", "Summary of Extension Skills of jQuery", "Summary of Drag and Drop Special Effects and Skills of jQuery", "Summary of Operation Skills of jQuery Table (table)", "Summary of Usage of Ajax in jquery", "Summary of Usage of Animation and Special Effects of jQuery" and "Usage of

I hope this article is helpful to everyone's jQuery programming.


Related articles: