码迷,mamicode.com
首页 > 其他好文 > 详细

淘宝放大镜

时间:2020-04-24 21:26:38      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:显示   需要   The   code   偏移量   use   hid   pre   尺寸   

监听事件来实现淘宝放大镜效果

html + css

<style>
    * { margin: 0; padding: 0; }
    .wrap {
	position: relative;
	width: 400px;
	height: 400px;
	margin: 20px;
    }
    /* 设置初始尺寸 */
    .wrap img { width: 400px; height: 400px; }
    .wrap .mark {
	display: none;	/* 默认隐藏 */
	position: absolute;
	left: 0;
	top: 0;
	width: 100px;
	height: 100px;
	background-color: rgb(0, 0, 0, .4);
    }
    .hiddenwrap {
	display: none;	/* 默认隐藏 */
	overflow: hidden;  /* 溢出隐藏 */
	position: absolute;
	top: 0;
	left: 450px;
	width: 600px;
	height: 600px;
    }
    /* 设置放大尺寸 */
    .hiddenwrap img { width: 1000px; height: 1000px; }
</style>

<div class="wrap">
    <img src="./images/scale.jpg">
    <div class="mark"></div>
</div>

<div class="hiddenwrap">
    <img src="./images/scale.jpg" >
</div>

js实现

const wrap = document.querySelector(‘.wrap‘)
const mark = document.querySelector(‘.mark‘)
const hdWrap = document.querySelector(‘.hiddenwrap‘)
const largeImg = document.getElementsByTagName(‘img‘)[1]
		
/* 监听鼠标移入事件 */
wrap.onmouseenter = function () {
    //显示放大镜
    mark.style.display = ‘block‘
    //让隐藏部分显示
    hdWrap.style.display = ‘block‘
    /* 监听鼠标移动 */
    window.onmousemove = function (e) {
	let left = e.pageX - wrap.offsetLeft - mark.clientWidth / 2
	let top = e.pageY - wrap.offsetTop - mark.clientHeight / 2
	let maxLeft = wrap.clientWidth - mark.clientWidth
	let maxTop = wrap.clientHeight - mark.clientHeight
	//对移动空间进行限制
	left >= maxLeft ? left = maxLeft : left = left,
	left <= 0 ? left = 0 : left = left
	top >= maxTop ? top = maxTop : top = top,
	top <= 0 ? top = 0 : top = top
	//让鼠标位于放大镜中心
	mark.style.left = left + ‘px‘
	mark.style.top = top + ‘px‘
	/*显示需要放大部分*/
	hdWrap.scrollLeft = left / maxLeft * (largeImg.clientWidth - hdWrap.clientWidth)
	hdWrap.scrollTop = top / maxTop * (largeImg.clientHeight - hdWrap.clientHeight)
    }
			
    /* 监听鼠标离开 */
    wrap.onmouseleave = function (e) {
	//隐藏放大镜
	mark.style.display = ‘none‘
	//隐藏放大图
	hdWrap.style.display = ‘none‘
	//移除监听
	window.onmousemove = null
	wrap.onmouseleave = null
    }
}
		
/* 今日知识点:
    * 计算放大图片的偏移量涉及一点数学运算
    * 初始的偏移量之比 = 放大的偏移量之比
*/		

淘宝放大镜

标签:显示   需要   The   code   偏移量   use   hid   pre   尺寸   

原文地址:https://www.cnblogs.com/sheep2/p/12770061.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!