js实现鼠标移动
 要求:
html結構部分
<!DOCTYPE html> <html lang="en"><head><title>Document</title><link rel="stylesheet" href="./css/fdj.css"></head><body><!-- 包裹整個項目的大盒子 --><div class="container"><!-- 放大鏡顯示的效果 --><div class="bigImg"><p></p></div><!-- 點擊顯示按鈕ul --><ul><li><img src="./images/show_1.jpg" alt=""></li><li><img src="./images/show_2.jpg" alt=""></li><li><img src="./images/show_3.jpg" alt=""></li><li><img src="./images/show_4.jpg" alt=""></li></ul></div><script src="./js/img.js"></script> </body> </html>css樣式
* {margin: 0;padding: 0; }.big {width: 300px;height: 300px;background-color: skyblue;position: relative;background: url(../images/show_1.jpg);/* background */ }.small {width: 100px;height: 100px;position: absolute;background-color: yellow;opacity:0.5;left: 0px;top: 0px;/* 當前元素事件不起作用 */pointer-events: none;display: none; } .container{width: 500px;height: 500px;/* background-color: pink; */ }ul{list-style: none; }ul li{width: 50px;height: 50px;background-color: red;margin-left: 20px;float: left; }ul li img{width: 50px; }js代碼部分
var divEle = document.querySelector('.bigImg') divEle.classList.add('big') var pEle = document.querySelector('p') pEle.classList.add('small')//給ulEle添加一個點擊事件 var ulEle = document.querySelector('ul') ulEle.addEventListener('click',function(e){e = e || window.eventlet target = e.target || e.srcElement//獲取到事件委托的圖片地址let url = target.getAttribute('src')divEle.style.background = `url(${url})`})//給大盒子綁定鼠標移動事件、返回移動值 divEle.onmousemove = function (e) {e = e || window.event //事件對象console.log('X ', e.offsetX, ' Y :', e.offsetY);//將現在的鼠標在的x,y值傳給小盒子,并讓鼠標永遠在小盒子中間var bigPosX = e.offsetX - pEle.clientWidth / 2var bigPosY = e.offsetY - pEle.clientHeight / 2// 小盒子的邊界問題//右邊界臨界值 = 大盒子的寬度 - 小盒子的寬度var maxRight = divEle.clientWidth - pEle.clientWidth//下邊界臨界值 = 大盒子的高度 - 小盒子的高度var maxBottom = divEle.clientHeight - pEle.clientHeight// 左邊界if (bigPosX < 0) {bigPosX = 0}//右邊界值if (bigPosX > maxRight) {bigPosX = maxRight}//上邊界值if (bigPosY < 0) {bigPosY = 0}//下邊界值if (bigPosY > maxBottom) {bigPosY = maxBottom}//將值賦值給小盒子的position的left和top屬性中去pEle.style.left = bigPosX + 'px' //將鼠標X軸的位置傳給小盒子的positionpEle.style.top = bigPosY + 'px' //將鼠標y軸的位置傳給小盒子的position }//小盒子隱藏顯示: 摸到大盒子顯示小盒子 divEle.onmouseover = function(){pEle.style.display = 'block' } divEle.onmouseout = function(){pEle.style.display = 'none' }總結
 
                            
                        - 上一篇: Error: Duplicate res
- 下一篇: iPhone 手势识别
