JS script controls the horizontal and vertical center of the picture

Source: Internet
Author: User

How to use:

1. Define the Resizeimg (obj) method

1 functionresizeimg (obj) {2     varBoxheight = $ (". Box"). Height ();3     varBoxwidth = $ (". Box"). width ();4     varImgHeight =$ (obj). Height ();5     varImgWidth =$ (obj). width ();6     if(ImgHeight * boxwidth >= imgwidth *boxheight) {7         //after adjustment, the height exceeds the situation8         varAfterimgheight = Boxwidth * ImgHeight/ImgWidth;9$ (obj). css ("width", boxwidth + "px"). CSS ("height", afterimgheight + "px"));Ten         varOffsetTop = (AFTERIMGHEIGHT/2)-(BOXHEIGHT/2); One$ (obj). CSS ("Top", "-" + OffsetTop + "px");//-20px A     } -     Else { -         //after adjustment, the width exceeds the situation the         varAfterimgwidth = Boxheight * ImgWidth/imgheight; -$ (obj). css ("height", boxheight + "px"). CSS ("width", afterimgwidth + "px")); -         varOffsetleft = (AFTERIMGWIDTH/2)-(BOXWIDTH/2); -$ (obj). css ("left", "-" + offsetleft + "px");//-20px +     } -Console.log ("resize OK.")); +}

2. In the IMG tag binding onload event processing method is resizeimg.

onload= "resizeimg(this)"/>

3. Note:

Do not set the width of the picture, high;

Need to set the image positioning properties, position:relative;

Effects such as:

JS script controls the horizontal and vertical center of the picture

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.