网站页面效果需要,理了个DEMO放在这里备用。
纯HTML代码如下:
<head>
<title>只能在指定区域能移动的层</title>
<style type="text/css">
*{margin:0px; padding:0px;}
#dvDragContiner { height: 70px; overflow: hidden; width: 300px; background: #bbb; position: relative; z-index: 0; }
#dvDragContiner .first { height: 8px; overflow: hidden; font-size: 0px; width: 250px; margin:0px auto;
background: #FFF; z-index: 1;margin-top: 31px; position: relative; }
#dvDragContiner .drag { height: 25px; width: 20px; background: red; cursor: pointer; position: absolute; top: 0px; z-index: 2; left: 25px; top: 22px; }
</style>
<script src="jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
var x = 0, y = 0;
var moveable = false;
var minLeft = 25;
var maxScrollWidth = 300 - 20 - 20;
$(function() {
var btIndex = document.all ? 1 : 0;
$("#dvDragContiner .drag").mousedown(function(evt) {
//alert('abc');
if (evt.button == btIndex) {
//$("#spOne").text("鼠标按下时的位置:x=" + evt.pageX + ",y=" + evt.pageY);
x = evt.clientX - parseInt($(this).css("left"));
//y = evt.clientY - parseInt($(this).css("top"));
moveable = true;
this.setCapture(); //重要
}
}).mouseup(function(evt) {
if (moveable) {
moveable = false;
this.releaseCapture(); //重要
}
}).mousemove(function(evt) {
var _x = evt.clientX;
var _movePiex = 0;
if (_x - x < minLeft) {
_movePiex = minLeft;
}
else if (_x - x > maxScrollWidth) {
_movePiex = maxScrollWidth;
}
else {
_movePiex = _x - x;
}
if (moveable) {
$(this).css({
//"top": evt.clientY - y + "px",
"left": _movePiex + "px"
})
}
});
});
</script>
</head>
<body>
<div id="dvDragContiner">
<div class="first">
</div>
<div class="drag" title="只能在白线区域内进行横向滑动">
</div>
</div>
</body>
</html>
效果图:
图中的红色滑块只能在白色区所绘的区间进行横向滑动。类似Winform中HSrollBar效果。在WEB中可扩展出任意风格的textarea。