$.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)); }); }; $("#floatdiv").css("left", $("#rolltop").position().left - 1120).smartFloat();
<div id="rolltop">回到顶部</div> <div id="floatdiv" style="position:absolute; top: 320px; width: 120px; height: 278px;background-color:#f00;"></div>
#rolltop { margin-right: -430px; position: fixed; right: 45%; top: 80%; width: 25px; background-color:#f00; }