AI智能
改变未来

html、css、js实现放大镜效果


放大镜

效果图:
【图片来自我最爱的阴阳师官网】

html:

<!DOCTYPE html><html><head><link rel=\"stylesheet\" href=\"style.css\"></head><body><div class=\"demo\"><!-- 小图 --><div class=\"small-box\"><!-- 放大镜 --><div class=\"float-box\"></div><img src=\"../1920x1080.jpg\" class=\'small-img\'/></div><!-- 显示 --><div class=\"big-box\"><img src=\"../1920x1080.jpg\"/></div></div></body><script src=\"static/index.js\"></script></html>

css:

* {margin: 0 ;padding: 0;}.demo {display: block;width: 400px;margin: 50px;position: relative;border: 1px solid #ccc;}.small-box {position: relative;z-index: 1;}.float-box {display: none;width: 160px;height: 120px;position: absolute;background: #ffffcc;border: 1px solid #ccc;opacity: 0.5;pointer-events: none;}.mark {position: absolute;display: block;width: 400px;height: 225px;background-color: #fff;opacity: 0;z-index: 10;}.small-img{width: 400px;display:block;}.big-box {display: none;position: absolute;top: 0;left: 460px;width: 400px;height: 300px;overflow: hidden;border: 1px solid #ccc;z-index: 1;pointer-events: none;}.big-box img {position: absolute;z-index: 5}

JavaScript:

window.onload = function () {var objDemo = document.getElementsByClassName(\"demo\")[0];var objSmallBox = document.getElementsByClassName(\"small-box\")[0];var objFloatBox = document.getElementsByClassName(\"float-box\")[0];var smallImg = document.getElementsByClassName(\"small-img\")[0];var objBigBox = document.getElementsByClassName(\"big-box\")[0];var objBigBoxImage = objBigBox.getElementsByTagName(\"img\")[0];//移入事件smallImg.onmouseover = function () {objFloatBox.style.display = \"block\"objBigBox.style.display = \"block\"}//移出事件smallImg.onmouseout = function () {objFloatBox.style.display = \"none\"objBigBox.style.display = \"none\"}//移动事件smallImg.onmousemove = function (ev) {var _event = ev || window.event;/* 获取鼠标中心点*/var left = _event.clientX - objDemo.offsetLeft - objSmallBox.offsetLeft - objFloatBox.offsetWidth / 2;var top = _event.clientY - objDemo.offsetTop - objSmallBox.offsetTop - objFloatBox.offsetHeight / 2;if (left < 0) {left = 0;} else if (left > (objSmallBox.offsetWidth - objFloatBox.offsetWidth)){left = objSmallBox.offsetWidth - objFloatBox.offsetWidth;}if (top < 0) {top = 0;} else if (top > (objSmallBox.offsetHeight - objFloatBox.offsetHeight)){top = objSmallBox.offsetHeight - objFloatBox.offsetHeight;}/* 放大镜的位置 */objFloatBox.style.left = left + \"px\";objFloatBox.style.top = top + \"px\";/* 计算百分比 */var percentX = left / (objSmallBox.offsetWidth - objFloatBox.offsetWidth);var percentY = top / (objSmallBox.offsetHeight - objFloatBox.offsetHeight);/* 显示图片相对应位置 */objBigBoxImage.style.left = -percentX * (objBigBoxImage.offsetWidth - objBigBox.offsetWidth) + \"px\";objBigBoxImage.style.top = -percentY * (objBigBoxImage.offsetHeight - objBigBox.offsetHeight) + \"px\";}}
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » html、css、js实现放大镜效果