The example of this article introduces the principle and code of magnifying glass based on JavaScript, and shares it for everyone's reference, the specific contents are as follows:
Principle:
A: Magnifying glass B: Small picture
C: Large picture visual area
D: Big picture
The mouse position should be in the center of the magnifying glass, so the mouse position is:
Clientx=a.offsetleft () +b.offsetleft+1/2*a.offsetwidth;
Clienty=a.offsettop () +b.offsettop+1/2*a.offsetheight;
During mouse movement: Magnifier A and Big D are all in proportion to the mouse movement, because when the right frame of Magnifier A is moved to coincide with the right border of small figure B, the large figure d should also move to the right border with the right border of C, so the proportion of their movement is : ( D.offsetwidth-c.offsetwidth)/(b.offsetwidth-a.offsetwidth) =b/a
HTML section:
JS section:
<script> window.onload=function () {var demo =document.getelementbyid (' demo '); var small =
document.getElementById (' small ');
var big =document.getelementbyid (' big '); var glass =document.getelementbyid (' glass ') var image =document.getelementbyid (' big '). getElementsByTagName (' img ') [0
];
var Zhezhao=document.getelementbyid (' Zhezhao '); Zhezhao.onmouseover=function () {glass.style.display= ' block ' big.style.display= ' block '} zhezhao.onmouseout=
function () {glass.style.display= ' none ' big.style.display= ' none '}//clear the relationship between the Clientx,offsetleft,left, pay attention to distinguish between Zhezhao.onmousemove=function (EV) {var event=ev var left=
EVENT.CLIENTX-DEMO.OFFSETLEFT-SMALL.OFFSETLEFT-GLASS.OFFSETWIDTH/2;
var top =event.clienty-demo.offsettop-small.offsettop-glass.offsetheight/2; if (left<0) {left=0;}
else if (left> (small.offsetwidth-glass.offsetwidth)) {left=small.offsetwidth-glass.offsetwidth} if (top<0) {
Top=0; }else if (top> (small.offsetheight-glass.offsetheight)) {top=small.offsetheight-glass.offsetheight}
Glass.style.left =left+ ' px ';
Glass.style.top =top+ ' px '; var percent= (image.offsetwidth-big.offsetwidth)/(Small.offsetwidth-glass.offsetwidth) image.style.left=-percent*
left+ ' px ' image.style.top =-percent*top+ ' px '}} </script>
The above is the entire contents of this article, I hope to achieve a JavaScript magnifier effect to help.