【问题标题】:Using javascript/jquery, how to do magnifying zoom on an image?使用 javascript/jquery,如何放大图像?
【发布时间】:2017-06-26 09:16:04
【问题描述】:

我正在尝试在鼠标悬停时放大图像。它应该看起来像跟随图像。不使用任何插件我怎么能做到这一点?

【问题讨论】:

标签: javascript jquery html css


【解决方案1】:

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

$(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

【讨论】:

  • 这很有帮助。但问题是,当图像动态添加到图像 url 中时。我如何替换 css 图片背景 url?
  • 要使用 JQuery 更改它,$(".large").css("background-image", "url('whatever.png')"); 或者您可以事先更改 css。
猜你喜欢
  • 2011-08-29
  • 2011-01-13
  • 1970-01-01
  • 2013-10-06
  • 2018-03-28
  • 2014-11-29
  • 2013-12-12
  • 2012-11-14
  • 1970-01-01
相关资源
最近更新 更多