每天学一个jquery插件-放大镜缩放

每天一个jquery插件-放大镜缩放

放大镜缩放

之前做过放大镜的效果,然后现在优化了一点点然后加了滚轮控制缩放比例的事件,希望对大家有启发

效果如下

代码部分


<html>
	<head>
		<meta charset="utf-8">
		<title>放大镜实现title>
		<script src="js/jquery-3.4.1.min.js">script>
		<style>
			* {
      
				margin: 0;
				padding: 0;
			}

			#div {
      
				width: 400px;
				height: 400px;
				margin: 20px;
				border: 1px solid lightgray;
				background-image: url(img/1.jpg);
				background-repeat: no-repeat;
				background-position: center center;
				background-size: 100% 100%;
			}

			.rel {
      
				z-index: 1;
				position: relative;
			}

			.glass {
      
				/* display: none; */
				border-radius: 50%;
				position: absolute;
				background-color: black;
				pointer-events: none;
				background-repeat: no-repeat;
				opacity: 0.95;
			}
		style>
	head>
	<body>
		<div id="div">

		div>
	body>
html>
<script>
	$(function() {
      
		$("#div").glass();
	})
	$.prototype.glass = function(op) {
      
		op = op == undefined ? {
      } : op;
		op.width = op.width == undefined ? 100 : op.width;
		op.height = op.height == undefined ? 100 : op.height;
		op.span = op.span == undefined ? 2 : op.span; //放大率
		op.wheel  =op.wheel==undefined?5:op.wheel;//滚轮的缩放率
		op.flag = undefined ? false : true; //是否允许滚轮控制缩放
		this.arrs().forEach(item => {
      
			var $that = $(item);
			$that.addClass('rel');
			var $glass = $("
"
); $glass.css(op); $glass.appendTo($that); $glass.hide(); var bimg = $that.css('background-image'); $glass.css({ 'background-image': bimg, 'background-size': ($that.width() * op.span) + 'px ' + ($that.height() * op.span) +'px' }); var x = 0; var y = 0; //放大镜效果 $that.mouseenter(function() { $glass.show(); }).mouseleave(function() { $glass.hide(); }).mousemove(function(e) { x = e.offsetX; y = e.offsetY; $glass.css({ 'left': x - op.width / 2, 'top': y - op.height / 2, 'background-position-x': (op.width / op.span - (x * op.span)) + 'px', 'background-position-y': (op.height / op.span - (y * op.span)) + 'px', 'background-size': ($that.width() * op.span) + 'px ' + ($that.height() * op.span) +'px' }) }).on('mousewheel', function(e) { var temp = (e.originalEvent.deltaY/op.wheel)/100; op.span +=temp; $glass.css({ 'left': x - op.width / 2, 'top': y - op.height / 2, 'background-position-x': (op.width / op.span - (x * op.span)) + 'px', 'background-position-y': (op.height / op.span - (y * op.span)) + 'px', 'background-size': ($that.width() * op.span) + 'px ' + ($that.height() * op.span) +'px' }) }) //滚轮控制缩放比例 }) } $.prototype.arrs = function() { var that = this; var arr = []; for (var i = 0; i < that.length; i++) { arr.push($(that[i])); } return arr; }
script>

思路解释

  • 思路不难,就是移动的时候能拿到一个相对的参数,我们在按照这个参数关联里面背景图片的位置摆放
  • 并且之前是容器里面套img标签做,起始单纯的div的背景图的background-属性里面也能达到一样的效果
  • 完事,休息

你可能感兴趣的:(每天学一个jquery插件,javascript,jquery)