JavaScript实现图片悬浮预览

一、前端页面中编辑控件展示图片来源路径。我这里是C# web项目的aspx页面,和HTML一样的,不同项目可以将代码中间的<%=path %>替换为实际项目中的图片来源路径变量。

<tr>
    <td>缩略图:</td>
    <td>
        <a href="<%=path %>" id="a1" class="tooltip">
        <img id="f1" src="<%=path %>" alt="1" width="80" height="80" />
        </a>
    </td>
</tr>

 二、编写JavaScript代码,当鼠标移动到指定控件时生成悬浮预览框。可以指定预览框的位置。

<script type="text/javascript">
    //图片预览
    $(function () {
        var x = 8;
        var y = 8;
        $("a.tooltip").mouseover(function (e) {
            //console.log(this.href);
            var pageHeight = $(document).height();
            var pageWidth = $(document).width();
            //console.log(pageHeight + "|" + pageWidth);
            var tooltip = "<div id='tooltip'><img src='" + this.href + "' alt='' /><\/div>"; //创建 div 元素
            $("body").append(tooltip);	//把它追加到文档中						 
            $("#tooltip")
                .css({
                    "bottom": (pageHeight - e.pageY) + "px",
                    "left": (e.pageX + x) + "px"
                }).show("fast");	  //设置x坐标和y坐标,并且显示

        }).mouseout(function () {
            $("#tooltip").remove();	 //移除 
        }).mousemove(function (e) {
            $("#tooltip")
                .css({
                    "bottom": (pageHeight - e.pageY) + "px",
                    "left": (e.pageX + x) + "px"
                });
        });
    });
</script>

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用JavaScript实现鼠标悬浮改变图片位置的效果,具体实现步骤如下: 1. 获取需要操作的图片元素和容器元素。 2. 添加鼠标悬浮事件监听器,当鼠标悬浮在容器元素上时,获取鼠标在容器内的位置。 3. 计算图片应该移动的距离,并设置图片的样式`transform: translate(x, y)`来实现移动效果。 以下是示例代码: ```html <style> .container { position: relative; width: 500px; height: 300px; border: 1px solid #333; overflow: hidden; } img { position: absolute; top: 0; left: 0; transition: transform 0.3s ease-out; } </style> <div class="container" onmousemove="moveImage(event)"> <img src="example.jpg" alt="example" /> </div> <script> const container = document.querySelector('.container'); const image = document.querySelector('img'); function moveImage(event) { const containerRect = container.getBoundingClientRect(); const mouseX = event.clientX - containerRect.left; const mouseY = event.clientY - containerRect.top; const centerX = containerRect.width / 2; const centerY = containerRect.height / 2; const moveX = (mouseX - centerX) / 10; const moveY = (mouseY - centerY) / 10; image.style.transform = `translate(${moveX}px, ${moveY}px)`; } </script> ``` 该示例代码中,将图片放在一个容器中,容器的宽高和边框用于限制图片移动的范围。当鼠标在容器内移动时,计算鼠标相对于容器中心的偏移量,使用该偏移量计算图片应该移动的距离,并使用`transform`样式来实现图片移动效果

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值