app开发定制今天来做一个非常常见app开发定制且有意思的的案例,app开发定制就是我们的鼠标经过图app开发定制片放大的一个效果!
app开发定制具体实现的效果看下面这张图
案例分析:
黄色的遮挡层跟随鼠标功能。
把鼠标坐标给遮挡层不合适。因为遮挡层坐标以父盒子为准。
首先是获得鼠标在盒子的坐标。
之后把数值给遮挡层做为left 和top值。
此时用到鼠标移动事件,但是还是在小图片盒子内移动。
发现,遮挡层位置不对,需要再减去盒子自身高度和宽度的一半。
遮挡层不能超出小图片盒子范围。
如果小于零,就把坐标设置为0
如果大于遮挡层最大的移动距离,就把坐标设置为最大的移动距离
遮挡层的最大移动距离:小图片盒子宽度 减去 遮挡层盒子宽度
这种类似放大镜的效果很多朋友肯定以为是一张图片的放大效果,其实我们这个地方是准备了两张图片,鼠标经过小图移动大图,这种神奇的效果就实现了。接下来我们仔细来分析一下这个效果该怎么写代码!
首先还是老规矩哈,在 body 里面把 html 框架搭好,引入两张图片。
- <div class="box">
- <img src="images/small.jpg" alt="" class="small">
- <div class="yy"></div>
- <div class="big">
- <img src="images/big.jpg" alt="">
- </div>
- </div>
这样写好了我们看不出任何效果,当然需要 css 的渲染!!!
- <style>
- .box {
- position: relative;
- width: 350px;
- height: 350px;
- }
-
- .yy {
- position: absolute;
- top: 0;
- left: 0;
- width: 250px;
- height: 250px;
- background-color: yellow;
- opacity: 0.5;
- border: 1px solid #333;
- display: none;
- }
-
- .big {
- position: absolute;
- left: 360px;
- top: 0px;
- width: 500px;
- height: 500px;
- overflow: hidden;
- display: none;
- }
-
- .big>img {
- position: absolute;
- top: 0;
- left: 0;
- }
- </style>
为了展示效果我在隐藏之前截了个图,基本框架搭好以后就是这个样子啦!当然,为了更好的实现效果,这里的大图和黄色遮挡层肯定是要隐藏的,我放在上面的代码已经提前写好了隐藏。
接下肯定就是用 JavaScript 来实现的页面交互效果了。鼠标经过隐藏,鼠标离开显示,以及鼠标在小图里面移动大图跟着移动的效果。这样就实现了一个放大镜的效果!!
- <script>
- window.addEventListener('load', function () {
- var box = document.querySelector('.box');
- var yy = document.querySelector('.yy');
- var big = document.querySelector('.big');
- box.addEventListener('mouseover', function () {
- yy.style.display = 'block';
- big.style.display = 'block';
- })
- box.addEventListener('mouseout', function () {
- yy.style.display = 'none';
- big.style.display = 'none';
- })
- box.addEventListener('mousemove', function (e) {
- var x = e.pageX - box.offsetLeft;
- var y = e.pageY - box.offsetTop;
- var width = x - yy.offsetWidth / 2;
- var height = y - yy.offsetHeight / 2;
- if (width <= 0) {
- width = 0;
- } else if (width >= box.offsetWidth - yy.offsetWidth) {
- width = 100;
- }
- if (height <= 0) {
- height = 0;
- } else if (height >= box.offsetHeight - yy.offsetHeight) {
- height = box.offsetHeight - yy.offsetHeight;
- }
- yy.style.left = width + 'px';
- yy.style.top = height + 'px';
- var bigimg = document.querySelector('.big>img');
- // 大图片的移动距离=遮挡层移动距离*大图片最大移动距离/遮挡层最大移动距离
- var bigx = width * (bigimg.offsetWidth - big.offsetWidth) / (box.offsetWidth - yy.offsetWidth);
- var bigy = height * (bigimg.offsetHeight - big.offsetHeight) / (box.offsetHeight - yy.offsetHeight);
- bigimg.style.left = -bigx + 'px';
- bigimg.style.top = -bigy + 'px';
- })
- })
- </script>
以上就是实现这一效果的全部代码了,感兴趣的朋友可以收藏哦,以后可就找不到这么优秀的文章了!!