本文的示例介绍了jQuery如何实现滚动鼠标放大和缩小图像。 分享给大家鼠标图片放大源码,供大家参考,具体如下:
在项目制作过程中,遇到了这样的需求,所以就开发了一个,记录下来。
首先,您需要定义 html 元素和 css 样式:
<pre class="brush:xhtml;">
在这种风格中,我将图像风格设置为670px。 目的是防止图片过大时显示在页面之外。
然后我用了一个jquery mousewheel插件来解决鼠标中键的滚动问题。 下面是具体的jquery操作代码:
$(document).ready(function() { var count = 0; $("#ctl00_ContentPlaceHolder1_myImg").hover(function(e) { var left = e.originalEvent.x || e.originalEvent.layerX || 0; //get the left position var top = e.originalEvent.y || e.originalEvent.layerY || 0; //get the top position $("#NotificationMsg").css({ 'position': 'absolute','left': left,'top': top }); $("#NotificationMsg").css("display","block"); },function() { //alert('mouserout'); $("#NotificationMsg").css("display","none"); }).mousewheel(function(event,delta,deltaX,deltaY) { count++; var height = $(this).attr("height"); //get initial height var width = $(this).attr("width"); // get initial width var stepex = height / width; //get the percentange of height / width var minHeight = 150; // min height var tempStep = 50; // evey step for scroll down or up $(this).removeAttr('style'); if (delta == 1) { //up $(this).attr("height",height + count * tempStep); $(this).attr("width",width + count * tempStep / stepex); } else if (delta == -1) { //down if (height > minHeight) $(this).attr("height",height - count * tempStep); else $(this).attr("height",tempStep); if (width > minHeight / stepex) $(this).attr("width",width - count * tempStep / stepex); else $(this).attr("width",tempStep / stepex); } event.preventDefault(); count = 0; }); });
这段代码中,使用originalEvent函数来获取鼠标的位置。 可用于IE9和firefox下测试:
var left = e.originalEvent.x || e.originalEvent.layerX || 0; //get the left position var top = e.originalEvent.y || e.originalEvent.layerY || 0; //get the top position
然后在代码中,我进行了如下操作来确定图像的初始高度和宽度以及图像显示的长宽比(目的是实现等缩放):
var height = $(this).attr("height"); //get initial height var width = $(this).attr("width"); // get initial width var stepex = height / width; //get the percentange of height / width var minHeight = 150; // min height var tempStep = 50; // every step for scrolling down or up $(this).removeAttr('style');
其中tempStep主要用于实现滚动时可以缩小和放大的比例值。 完成此操作后,我删除了图像的宽度样式,主要是为了能够放大或缩小。
if (delta == 1) { //up $(this).attr("height",height + count * tempStep); $(this).attr("width",width + count * tempStep / stepex); } else if (delta == -1) { //down if (height > minHeight) $(this).attr("height",height - count * tempStep); else $(this).attr("height",tempStep); if (width > minHeight / stepex) $(this).attr("width",width - count * tempStep / stepex); else $(this).attr("width",tempStep / stepex); } event.preventDefault(); count = 0;
上面这段话比较简单。 主要是通过上下滚动来判断鼠标图片放大源码,然后等比例放大或缩小图像。 event.preventDefault() 可以保证图像滚动时页面不会滚动。
附上这个插件: