js实现放大镜效果(附css样式)

2017-05-26  本文已影响0人  无敌万小奔

CSS样式

<style>

* {

margin:0;

padding:0;

}

img {

vertical-align: top;

}

.box {

width: 350px;

height: 350px;

margin: 100px;

border:1px solid #ccc;

position: relative;

}

.big {

width: 450px;

height: 450px;

border:1px solid #ccc;

position: absolute;

top:0;

left: 360px;

overflow: hidden;

display: none;

}

.mask {

width: 100px;

height: 100px;

background: rgba(255,255,0,.4);

position: absolute;

top: 0;

left: 0;

cursor: move;

display: none;

}

.small {

position: relative;

}

.big img {

position: absolute;

top: 0;

left: 0;

}

</style>

</head>

html结构


<body>

<div class="box" id="fdj">

<!--小图片-->

<div class="small">

![](./images/001.jpg)

<div class="mask"></div>

</div>

<!-- 大图片 -->

<div class="big">

![](./images/0001.jpg)

</div>

</div>

</body>

javascript代码如下

<script>

//js功能实现

var fdj = document.getElementById('fdj');//找到最外层的box

var small = fdj.children[0];//找到小盒子

var big = fdj.children[1];//找到大图片的盒子

var mask = small.children[1];//找到黄色小盒子

var bigImage = big.children[0];//找到大盒子中的图片

//设置两个变量,用来承载位置信息

var x = null;

var y = null;

//当鼠标滑到small身上的时候,让黄色小盒子和大图片显示出来

small.onmouseover = function (){

mask.style.display = 'block';

big.style.display = 'block';

}

//当鼠标移出small身上的时候,让黄色盒子和大图片盒子消失

small.onmouseout = function(){

mask.style.display = 'none';

big.style.display = 'none';

}

small.onmousemove = function (event){

var event = event || window.event;//兼容

//offsetParent 表示获取当前元素上一层具有定位的父级元素

console.log(this.offsetParent.offsetLeft);//box

//offsetWidth 当前元素的整体宽度 包括滚动条

console.log(mask.offsetWidth);

console.log(event.clientX);

x = event.clientX - this.offsetParent.offsetLeft - mask.offsetWidth / 2;

y = event.clientY - this.offsetParent.offsetTop - mask.offsetHeight / 2;

//判断,当鼠标移出盒子的时候,让黄色盒子停止移动

if(x<0){

x=0;

}else if(x > small.offsetWidth - mask.offsetWidth){

x = small.offsetWidth - mask.offsetWidth;

}

if(y<0){

y=0;

}else if(y > small.offsetHeight - mask.offsetHeight){

y = small.offsetHeight - mask.offsetHeight;

}

//让黄色盒子移动

mask.style.left = x + 'px';

mask.style.top = y + 'px';

// 沈钰 dav

// 2 4

// 3 6

// 100 300

// 300 900

// 大图片(800)所在的盒子 450 小图片 350 450 / 350 x * 450/350

bigImage.style.left = -x * big.offsetWidth / small.offsetWidth + 'px';

bigImage.style.top = -y * big.offsetHeight / small.offsetHeight + 'px';

}

</script>

上一篇下一篇

猜你喜欢

热点阅读