标签:
HTML代码:
div.box>span+div
CSS代码:
box相对定位,span在box内绝对定位,div绝对定位超出其自身宽
.box{ width:350px; height:350px; background: url(images/xiaotu.jpg) 0 0 no-repeat; margin:100px; border:1px solid #000; position: relative; } .box span{ width:150px; height:150px; background: red; position: absolute; left:0; top:0; opacity:0.3; cursor:move; display:none; } .box div{ width:400px; height:400px; background: url(images/datu.jpg) 0 0 no-repeat; border:1px solid #000; position: absolute; right:-420px; top:0; display:none; }
JQ代码:
<script>
//将span限制在box中拖拽,同时根据span拖拽的坐标来对应div大图中的坐标
$(function(){
var divX = $(‘.box‘).offset().left;
var divY = $(‘.box‘).offset().top;
var w1 = $(‘span‘).width();
var h1 = $(‘span‘).height();
var w2 = $(‘.box‘).width();
var h2 = $(‘.box‘).height();
$(‘.box‘).mouseover(function(event) {
$(‘.box span,.box div‘).show();
//鼠标移动
$(‘.box‘).mousemove(function(event) {
//获取鼠标坐标
var mx = event.pageX;
var my = event.pageY;
//拖拽点
var x = mx-divX-75;
var y = my-divY-75;
if(x<0){
x=0;
}
if(y<0){
y=0;
}
if(x>w2-w1){
x=w2-w1;
}
if(y>h2-h1){
y=h2-h1;
}
//对应div背景的坐标
var posX = 800*x/350;
var posY = 800*y/350;
$(‘span‘).css({left:x,top:y});
$(‘.box div‘).css({
backgroundPosition:(-posX)+‘px ‘+(-posY)+‘px‘
});
});
});
//离开box后,事件消失
$(‘.box‘).mouseout(function(event) {
$(‘.box span,.box div‘).hide();
});
})
</script>
标签:
原文地址:http://www.cnblogs.com/shisanjun/p/4819991.html