我想我有你需要的。我设法定位绿色子元素 ( #container2
),使其在水平滚动时保持固定,然后在内部内容垂直滚动时保持其水平偏移。
jQuery是:
var $container = $("#container");
var $content1 = $("#content1");
var $content2 = $("#content2");
var content2InitTop = $content2.offset().top;
var content2InitLeft = $content2.offset().left;
$container.on('scroll', function () {
var scrollTop = $(this).scrollTop();
var scrollLeft = $(this).scrollLeft();
if (scrollLeft == 0 && scrollTop == 0) {
$content2.removeClass('fixed');
$content2.offset({
'top': content2InitTop,
'left': content2InitLeft
});
}
if (scrollLeft > 0) {
$content2.addClass('fixed');
$content2.offset({
'top': content2InitTop - scrollTop
});
}
if (scrollTop > 0) {
$content2.removeClass('fixed');
$content2.offset({
'top': content2InitTop - scrollTop,
'left': content2InitLeft
});
} else {
$content2.offset({
'left': content2InitLeft
});
}
});
CSS是:
div, body {
margin : 0px;
padding : 0px;
border : 0px;
}
#container {
width: 400px;
height: 200px;
margin: 45px;
overflow: auto;
border: 5px solid pink;
}
#inner {
width: 800px;
height: 500px;
position: relative;
}
#content1 {
width: 300px;
height: 50px;
background-color: red;
}
#content2 {
width: 150px;
height: 50px;
background-color: green;
margin-top: 10px;
position: absolute;
}
#content2.fixed {
position: fixed;
background-color: lightgreen;
}
演示小提琴是:http: //jsfiddle.net/audetwebdesign/7Aw6M/