我有一个添加了position: sticky
的侧边栏,但是当我滚动到某个点时它会停止粘贴?!
在Chrome版本中测试:版本61.0.3163.100和Safari版本:11.0
HTML:
<div class="sticky">
this should stick!
</div>
<div class="content">
this is content
</div>
CSS:
<style media="screen">
.sticky {
background-color: #ccc;
position: -webkit-sticky;
position: -moz-sticky;
position: -ms-sticky;
position: -o-sticky;
position: sticky;
top: 15px;
width: 100px;
float: left;
}
.content{
background-color: #eee;
height: 3000px;
width: 700px;
float: right;
}
</style>
答案 0 :(得分:2)
position: sticky;
您可以尝试这样的事情:
<强> HTML 强>:
<div class="sticky-block">
this should stick!
</div>
<强> CSS 强>:
.sticky {
position: fixed;
top: 15px;
}
<强> JS 强>:
var $stickyBlock = document.querySelector('.sticky-block');
var origOffsetY = $stickyBlock.offsetTop - 15; // 15 is your top margin
function onScroll() {
window.scrollY >= origOffsetY ? $stickyBlock.classList.add('sticky') :
$stickyBlock.classList.remove('sticky');
}
document.addEventListener('scroll', onScroll);
或 jQuery :
var $stickyBlock = $('.sticky-block');
var origOffsetY = $stickyBlock.offset().top - 15; // 15 is your top margin
function onScroll() {
window.scrollY >= origOffsetY ? $stickyBlock.addClass('sticky') :
$stickyBlock.removeClass('sticky');
}
$(document).on('scroll', onScroll);
答案 1 :(得分:2)
在这里,试试这个,我会说它更好,而不是使用“粘性”,它不使用Jquery或任何简单的位置固定。
HTML
<div class="sticky">
this should stick!
</div>
<div class="content">
this is content
</div>
的CSS
.sticky {
background-color: #ccc;
top: 15px;
width: 100px;
float: left;
position:fixed;
}
.content{
background-color: #eee;
height: 3000px;
width: 700px;
float: right;
}
答案 2 :(得分:0)
我在jsfiddle上测试了你的代码,在这里,它可能是你的屏幕媒体查询导致你的问题。看看我的粘贴版本。我希望它能解决你的问题。
.sticky {
background-color: #ccc;
color:red;
position: sticky;/* required */
position: -webkit-sticky;/* required */
top: 15px; /* required */
float:left;
}
.content{
background-color: #eee;
height: 3000px;
width: 700px;
float right;
}
&#13;
<div class="sticky">
this should stick!
</div>
<div class="content">
this is content
</div>
&#13;