javascript - 使用javascript/jquery,如何对图像进行放大缩放?

标签 javascript jquery html css

我试图在鼠标悬停时放大图像。它应该看起来像下面的图像。我如何在不使用任何插件的情况下做到这一点?

enter image description here

最佳答案

试试这个,它使用两个不同的图像,一个小的图像,然后是同一图像的放大版本。

$(document).ready(function(){
  var native_width = 0;
  var native_height = 0;
  $(".magnify").mousemove(function(e) {
    if(!native_width && !native_height) {
	  var image_object = new Image();
	  image_object.src = $(".small").attr("src");

	  native_width = image_object.width;
	  native_height = image_object.height;
    } else {
	  var magnify_offset = $(this).offset();
	  var mx = e.pageX - magnify_offset.left;
	  var my = e.pageY - magnify_offset.top;
			
	  if(mx < $(this).width() && my < $(this).height() && mx > 0 && my > 0) {
		$(".large").fadeIn(100);
	  } else {
		$(".large").fadeOut(100);
	  }
	  if($(".large").is(":visible")) {
		var rx = Math.round(mx/$(".small").width()*native_width - $(".large").width()/2)*-1;
		var ry = Math.round(my/$(".small").height()*native_height - $(".large").height()/2)*-1;
		var bgp = rx + "px " + ry + "px";
				
		var px = mx - $(".large").width()/2;
				var py = my - $(".large").height()/2;

		$(".large").css({left: px, top: py, backgroundPosition: bgp});
	  }
	}
  });
});
* {
  margin: 0; 
  padding: 0;
}

.magnify {
  width: 200px; 
  margin: 50px auto; 
  position: relative;
}

.large {
  width: 175px; height: 175px;
  position: absolute;
	
  box-shadow: 0 0 0 7px rgba(255, 255, 255, 0.85), 
	0 0 7px 7px rgba(0, 0, 0, 0.25), 
  inset 0 0 40px 2px rgba(0, 0, 0, 0.25);
	
  background: url('http://thecodeplayer.com/uploads/media/iphone.jpg') no-repeat;
  display: none;
}

.small { display: block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="magnify">
<div class="large"></div>
<img class="small" src="http://thecodeplayer.com/uploads/media/iphone.jpg" width="200"/>
</div>

修改自:http://thecodeplayer.com/walkthrough/magnifying-glass-for-images-using-jquery-and-css3

关于javascript - 使用javascript/jquery,如何对图像进行放大缩放?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42118462/

相关文章:

javascript - 如何使用 jQuery 动态获取产品名称和图像?

javascript - 如何从一种方法中替换另一种方法中的变量

javascript - 在滚动条上显示一系列图像

jquery - 如何在运行时应用 css 属性?

jQuery 在固定 div 上滑动切换

html - 垂直对齐菜单与表格显示

Javascript 或 PHP 后退按钮

javascript - 实现用户登录系统的正确方法

javascript - 将数组值从 html 传递到 flash 数组

javascript - 更改 jquery ui 进度条的值