js原生放大鏡
body體里的代碼
<div class="left"> //左邊的大div
<img src="./images/dali.jpg" width="100%" height="100%">
<div class="mask"></div> //放大鏡的小塊
</div>
<div class="right"> //右邊的大div
<img src="./images/dali.jpg">
</div>
css樣式代碼
//給左右兩個div設定樣式
.left, .right{
width: 340px;
height: 500px;
border:1px solid red;
float:left;
margin-right:70px;
position: relative;
}
//讓右邊的圖片超出隱藏
//最開始默認不顯示,當滑鼠進入才讓他顯示
.right {
overflow: hidden;
display: none;
}
//放大鏡的樣式
//默認不顯示,滑鼠進入顯示
.mask {
width: 50px;
height: 50px;
background-color: rgba(0,0,255,0.5);
position: absolute;
left:0px;
top:0px;
display: none;
}
一定要給放大鏡設定定位屬性,放大鏡的移動原理就是利用,定位后修改他的top和left的值,
js代碼
window.onload = function(){ //等頁面加載完在執行js代碼,防止圖片沒有加載好獲取不到值
// 獲取元素節點
let leftDiv = document.querySelector('.left')
let mask = document.querySelector('.mask')
let rightDiv = document.querySelector('.right')
let bigImg = document.querySelector('.right img')
// 2.小色塊跟隨滑鼠移動
leftDiv.onmousemove = function(e){
let x = 0
let y = 0
if (e.target == mask) {
x = e.offsetX + mask.offsetLeft
y = e.offsetY + mask.offsetTop
} else {
x = e.offsetX
y = e.offsetY
}
// 讓滑鼠顯示在色塊中心
x = x - mask.offsetWidth/2
y = y - mask.offsetHeight/2
// 防止坐標超出邊界
let maxLeft = leftDiv.offsetWidth - mask.offsetWidth
if (x < 0) {
x = 0
} else if (x > maxLeft) {
x = maxLeft
}
let maxTop = leftDiv.offsetHeight - mask.offsetHeight
if (y < 0) {
y = 0
} else if (y > maxTop) {
y = maxTop
}
mask.style.left = x + 'px'
mask.style.top = y + 'px'
// 左邊橫向移動的百分比
let perX = - x / leftDiv.offsetWidth * 100 + '%'
// 左邊堅向移動的百分比
let perY = - y / leftDiv.offsetHeight * 100 + '%'
// console.log(perX,'----',perY)
bigImg.style.transform = `translate(${perX},${perY})`
}
// 3.滑鼠移入和移出
leftDiv.onmouseenter = function(){
mask.style.display = 'block'
rightDiv.style.display = 'block'
// 1.計算小色塊尺寸
let w = leftDiv.offsetWidth * rightDiv.offsetWidth / bigImg.offsetWidth
let h = leftDiv.offsetHeight * rightDiv.offsetHeight / bigImg.offsetHeight
mask.style.width = w + 'px'
mask.style.height = h + 'px'
}
leftDiv.onmouseleave = function(){
mask.style.display = 'none'
rightDiv.style.display = 'none'
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/204900.html
標籤:其他
上一篇:jQuery是什么?和它的優缺點
下一篇:CSS定位
