jquery使用div实现滚动条效果(一)

2014-11-24 02:03:58 · 作者: · 浏览: 0

查了些div实现滚动条的效果,看了很多,大多都不符合要求。

要求如下:

1.div大小固定,div中内容大小不固定

2.鼠标移动到内容上时,如果内容太大,则出现滚动条,并可以拖动查看,而内容宽度不变。否则不显示滚动条。

如果纯粹的使用div的overflow-y:scroll,那么内容的宽度会变小。

废话不多说,直接上代码。

文章中导入jquery-1.4.1.min.js

js代码如下:

Js代码代码

<script type="text/java script" src="js/jquery-1.4.1.min.js">

<script type="text/java script">

var check = false;//是否可移动

$(document).ready(function(){

var h = $("#scrollContent").height();

var ih = $("#divcontent").height();

var mh = parseInt(h*h/ih);

var h1 = parseInt($("#ypThumbContainer").height())-mh;//图片与div的高度差值

var h2 = parseInt(ih - h);//内容与边框div的高度差值

$("#scrollContent").hover(function(){

if(ih > h){

$("#ypThumbContainer").show("slow");

$("#ypThumb").find("img").height(mh);

$("#ypThumb").show("slow");

//begin

var oDiv = document.getElementById("ypThumbContainer");

var oDiv2 = document.getElementById("ypThumb");

var mouseStart={};

var divStart={};

var rightStart={};

var bottomStart={};

$(oDiv2).mousedown(function(ev){

var oEvent = ev||event;

mouseStart.x = oEvent.clientX;

mouseStart.y = oEvent.clientY;

divStart.x = parseInt($(oDiv2).css("left"));

divStart.y = parseInt($(oDiv2).css("top"));

if(oDiv2.setCapture){

oDiv2.setCapture();

oDiv2.onmousemove = doDrag3;

oDiv2.onmouseup = stopDrag3;

}else{

$(oDiv).bind("mousemove",doDrag3).bind("mouseup",stopDrag3);

}

oEvent.preventDefault();

});

function doDrag3(ev) {

var oEvent = ev||event;

var t = oEvent.clientY-mouseStart.y+divStart.y;

if(t < 0){

t = 0;

}else if(t >= $(oDiv).height()-$(oDiv2).height()){

t = $(oDiv).height()-$(oDiv2).height();

}

$(oDiv2).css("top",t+"px");

$("#divcontent").css("top",-(t*h2/h1)+"px");

}

function stopDrag3(){

if(oDiv2.releaseCapture){

oDiv2.releaseCapture();

oDiv2.onmousemove = null;

oDiv2.onmouseup = null;

}else{

$(oDiv).unbind("mousemove",doDrag3).unbind("mouseup",stopDrag3);

}