本文示範一個實用的互動元件:透過拖動下方的滑塊,即時縮放上方預覽區中的圖片。這裡把功能拆成兩個建構函式——PicView 負責圖片縮放,Slider 負責滑塊的拖動與比例回傳,兩者透過回呼函式串接起來。
復制代碼 代碼如下:<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta http-equiv=Content-Type content="text/html;charset=gb2312">
<title>js拖動滑塊控制圖片顯示大小</title>
<style>
*{margin:0;padding:0;font-size:12px;}
#picViewPanel{margin:5px 50px 0 50px; width:328px; height:248px; overflow:auto; text-align:center; border:solid 1px #cccccc;}
#slider{margin:0 50px; height:15px; width:328px; border:1px solid #000000; position:relative;}
#sliderBlock{height:13px; width:50px; border:1px solid #cccccc; position:absolute; top:0; left:113px; cursor:pointer; background:#cccccc; text-align:center;}
</style>
</head>
<body>
<div id="picViewPanel"></div>
<div id="slider">
<span id="sliderLeft"><<<</span>
<span id="sliderRight">>>></span>
<span id="sliderBlock">==</span>
</div>
<script>
var pv = null;
var sd = null;
window.onload = function(){
pv = new PicView("/images/m01.jpg");
sd = new Slider(
function(p){
document.getElementById("sliderBlock").innerHTML = 2*p + "%";
pv.expand(2*p/100);
}, function(){});
};
var PicView = function(url, alt){
this.url = url; this.obj = null; this.alt = alt ? alt : "";
this.realWidth = null; this.realHeight = null; this.zoom = 1;
this.init();
};
PicView.prototype.init = function(){
var _img = document.createElement("img");
_img.src = this.url; _img.alt = this.alt; _img.style.zoom = this.zoom;
document.getElementById("picViewPanel").appendChild(_img);
this.obj = _img;
this.realWidth = _img.offsetWidth; this.realHeight = _img.offsetHeight;
};
PicView.prototype.reBind = function(){
this.obj.style.width = this.realWidth * this.zoom + "px";
this.obj.style.height = this.realHeight * this.zoom + "px";
};
PicView.prototype.expand = function(n){ this.zoom = n; this.reBind(); };
var Slider = function(ing, ed){
this.block = document.getElementById("sliderBlock");
this.percent = 0; this.value = 0; this.ing = ing; this.ed = ed;
this.init();
};
Slider.prototype.init = function(){
var _sx = 0, _cx = 0;
var o = this.block; var me = this;
o.onmousedown = function(e){
var e = window.event || e;
_sx = o.offsetLeft; _cx = e.clientX - _sx;
document.body.onmousemove = move;
document.body.onmouseup = up;
};
function move(e){
var e = window.event || e;
var pos_x = e.clientX - _cx;
pos_x = pos_x < 13 ? 13 : pos_x;
pos_x = pos_x > 213 ? 213 : pos_x;
o.style.left = pos_x + "px";
me.percent = (pos_x - 13) / 2;
me.ing(me.percent);
};
function up(){
document.body.onmousemove = function(){};
document.body.onmouseup = function(){};
}
};
</script>
</body>
</html>
運作流程是:滑塊移動時計算出百分比,透過回呼呼叫 PicView.expand 依比例重設圖片的寬高,達到即時縮放的效果。這種「元件化」的寫法讓縮放與拖動邏輯彼此獨立,維護起來更清爽。