滚动拖拽
最近我们第一电动网改版了,现在已完成三分之一,把目前三分之一主要的实现功能总结下
- 主要有滚动拖拽,分页,轮播图,滚动侦测,select框联动,日历,友好时间,评论等等
第一个总结功能是滚动拖拽
主要实现的点有
- 可以拖拽
- 可以滚动
代码块
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
<style>
*{
padding: 0;
margin: 0;
}
.wrap{
background: #e5e5e5;
width: 200px;
height: 400px;
overflow: hidden;
position: relative;
top: 200px;
left: 300px;
}
.cont{
position: absolute;
top: 0;
right: 0;
width: 100%;
}
li{
height: 80px;
}
.bg{
position: absolute;
top: 0;
right: 0;
background: #000;
opacity: 0.5;
width: 10px;
height: 100%;
visibility: hidden;
}
.bar{
position: absolute;
top: 0;
right: 0;
width: 10px;
height: 100px;
background: #fff;
}
</style>
</head>
<body>
<div class="wrap">
<div class="cont">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
</div>
<div class="bg">
<div class="bar"></div>
</div>
</div>
</body>
</html>
<script>
function allS() {
var $wrap = $('.wrap');//整个区块
var $cont=$('.cont');//内容区块
var $bg = $('.bg');//滚动的条的背景
var $bar =$('.bar');//滚动的条
var $doc = $(document);
ratio = $wrap.height()/$cont.height();
if(ratio<1){
//如果内容区块大于整个区块,鼠标移入hover,并重新计算滚动条的高度
flash_hover($wrap,$bg);
$bar.css('height',ratio*$bg.height());
}else {
//如果内容区块小于整个区块,那么滚动条区域隐藏,并且不需要执行拖拽和滚动
$wrap.css('height',$cont.height());
return false;
}
//拖拽事件
$bar.on('mousedown',function (ev) {
var oEvent = ev||event;
var disY =oEvent.clientY - this.offsetTop;
$doc.on('mousemove',function (ev) {
var oEvent = ev||event;
var newTop = oEvent.clientY - disY;
//滚动条滚动区域
if (newTop<=0){
newTop=0;
}
if(newTop>=$bg.height()-$bar.height()){
newTop = $bg.height()-$bar.height();
}
$bar.css('top',newTop);
scale = newTop/($bg.height()-$bar.height());
$cont.css('top',scale*($wrap.height()-$cont.height()));
});
$doc.on('mouseup',function () {
$doc.off();
});
return false;
});
function addwheel(obj,fn) {
//函数的作用是检测向下滚动还是向上滚动
function fnwheel(ev) {
var oEvent = ev||event;
var bDown = true //true向下
if(oEvent.wheelDelta){
if(oEvent.wheelDelta>0){
bDown = false;
}else{
bDown = true;
}
}else {
// 处理火狐兼容性
if (oEvent.detail>0){
bDown = true
}else {
bDown = false;
}
}
fn&&fn(bDown);
oEvent.preventDefault&&oEvent.preventDefault();
return false;
}
if (window.navigator.userAgent.indexOf('Firefox')!=-1){
//用于处理火狐兼容性
obj[0].addEventListener('DOMMouseScroll',fnwheel,false);
}else{
obj[0].onmousewheel = fnwheel;
}
}
//hover事件
function flash_hover(a,c){
a.hover(function () {
c.css('visibility','visible');
},function () {
c.css('visibility','hidden');
});
}
//滚动事件
addwheel($wrap,function (bok) {
console.log(bok);
var t = $bar[0].offsetTop;
//每次滚动多少px
if(bok){
t+=10;
}else {
t-=10;
}
//滚动的范围
if(t<=0){
t = 0
}
if(t>=$bg.height()-$bar.height()){
t=$bg.height()-$bar.height();
}
$bar.css('top',t);
scale = t/($bg.height()-$bar.height());
$cont.css('top',scale*($wrap.height()-$cont.height()));
})
}
allS();
</script>