如何在滚动上修复div [英] How to fix div on scroll
本文介绍了如何在滚动上修复div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果您在以下URL中向下滚动页面,则 share div将锁定到浏览器:
If you scroll down the page in the following URL, the 'share' div will lock onto the browser:
http://knowyourmeme.com/memes/pizza-is-a-vegetable
我假设他们正在应用 position:fixed;
属性。
I'm assuming they are applying a position: fixed;
attribute. How can this be achieved with jQuery?
推荐答案
您可以在下面找到一个示例。基本上,您在 window
的 scroll
事件中附加了一个函数并跟踪 scrollTop
属性,如果它高于期望的阈值,则应用位置:固定
和其他一些CSS属性。
You can find an example below. Basically you attach a function to window
's scroll
event and trace scrollTop
property and if it's higher than desired threshold you apply position: fixed
and some other css properties.
jQuery(function($) {
$(window).scroll(function fix_element() {
$('#target').css(
$(window).scrollTop() > 100
? { 'position': 'fixed', 'top': '10px' }
: { 'position': 'relative', 'top': 'auto' }
);
return fix_element;
}());
});
body {
height: 2000px;
padding-top: 100px;
}
code {
padding: 5px;
background: #efefef;
}
#target {
color: #c00;
font: 15px arial;
padding: 10px;
margin: 10px;
border: 1px solid #c00;
width: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="target">This <code>div</code> is going to be fixed</div>
这篇关于如何在滚动上修复div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文