放大镜案例

原理:
  • 该案例主要利用的就是鼠标事件来实现的,主要用到onmousemove和onmouseleave,如果对于这两个事件不明白的可以看看我总结的相关方法:事件处理(二)
  • 其次需要注意的是一是边界值问题,二是要明白鼠标移动的方向与所要放大的区域所移动的方向是相反的
最后代码如下:
	<div class="small">
        <div class="fangdajing"></div>
    </div>
    <div class="big">
        <img src="img/img.png" width="2000px" height="2000px" alt="" />
    </div>
<style>
        * {
            margin: 0;
            padding: 0;
        }
        
        .small {
            float: left;
            background-image: url('img/img.png');
            width: 400px;
            height: 400px;
            position: relative;
        }
        
        .small .fangdajing {
            width: 100px;
            height: 100px;
            background-color: rgba(185, 65, 64, 0.5);
            position: absolute;
        }
        
        .big {
            float: left;
            width: 400px;
            height: 400px;
            /* 溢出部分隐藏 */
            overflow: hidden;
            position: relative;
        }
        
        img {
            position: absolute;
        }
</style>
<script>
	//得到元素
	var smallDiv = document.querySeletor('.small');
	var fangdajing= document.querySeletor('.fangdajing');
	var bigDiv = document.querySeletor('.big');
	var img= document.querySeletor('img');
	
	//鼠标移动事件
	smallDiv.onmousemove = function(eve){
		var e = eve || windown.eve;
	
		//获得鼠标的坐标
		var shubiaoLeft = e.clientX;
		var shubiaoTop = e.clientY;

		//设置边界值
		if(shubiaoLeft < 50){
			shubiaoLeft = 50;
			}
		if(shubiaoLeft > 350){
			shubiaoLeft = 350;
			}
		if(shubiaoTop < 50){
			shubiaoTop = 50;
			}
		if(shubiaoTop > 350){
			shubiaoTop = 350;
			}
		
		//赋值给放大镜
		fangdajing.style.left = shubiaoLeft - 50 + 'px';
		fangdajing.style.top= shubiaoTop - 50 + 'px';

		/**
     * 让图片跟随放大镜移动
     * 注意:
     *      此时也应该注意,放大镜若向右走时,那么图片应该向左走;反之图片向右走
     *      big与img是1:5的关系
     */
		img.style.left = (-5) * shubiaoLeft + 'px';
		img.style.top= (-5) * shubiaoTop + 'px';

		//设置相关属性
		fangdajing.style.display = 'block';
		bigDiv.style.display = 'block';
	}

		//鼠标离开事件
		smallDiv.onmouseleave = function(){
			fangdajing.style.display = 'none';
			bigDiv.style.display = 'none';
		}

<script>

效果图如下:
请添加图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小白小白从不日白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值