<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no"/>
<meta http-equiv="x-ua-compatible" content="IE=edge"/>
<meta name="renderer" content="webkit">
<title>頁面滾動到中間兩個div向中間靠攏</title>
<style type="text/css">
* {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
margin: 0;
padding: 0;
font-family: '微軟雅黑', 'Microsoft Yahei';
}
body {
width: 100%;
overflow-x: hidden;
background: #fff;
position: relative;
}
h1, h2, h3, h4, h5, h6, p, ul, ol, dl, dd {
list-style: none;
}
.main_box {
width: 100%;
padding-bottom: 10px;
}
.div1200_pd {
width: 1200px;
margin: 0 auto;
min-height: 450px;
/*overflow: hidden;*/
position: relative;
padding-top: 40px;
padding-bottom: 40px;
}
</style>
<style>
.div_block{
width: 46%;
height: 200px;
top: 50%;
margin-top: -100px;
position: absolute;
background: #1e4ca1;
transition: .3s;
opacity:0;
}
#block1, #block3{
left: -800px;
}
#block2, #block4{
right: -800px;
}
.left_block{
left:0!important;
opacity: 1!important;
}
.right_block{
right:0!important;
opacity: 1!important;
}
</style>
</head>
<body>
<div class="main_box">
<div class="div1200_pd">
其它內容
</div>
<div class="div1200_pd">
<div id="block1" class="div_block">內容1</div>
<div id="block2" class="div_block">內容2</div>
</div>
<div class="div1200_pd">
其它內容
</div>
<div class="div1200_pd">
<div id="block3" class="div_block">內容3</div>
<div id="block4" class="div_block">內容4</div>
</div>
<div class="div1200_pd">
其它內容
</div>
</div>
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<script>
$(function () {
//頁面滾動到中間兩個div向中間靠攏
function lrToCenter(el,elclass) {
var elOffTop =$(el).offset().top;
var halfWinHeight=($(window).height())/2;
$(window).scroll(function(){
var _top = $(window).scrollTop();
if(_top >elOffTop-halfWinHeight){
$(el).addClass(elclass);
}
});
}
lrToCenter("#block1","left_block");
lrToCenter("#block3","left_block");
lrToCenter("#block2","right_block");
lrToCenter("#block4","right_block");
});
</script>
</body>
</html>