jquery_jquery를 기반으로 하는 autoIMG 이미지 적응형 플러그인 코드

WBOY
풀어 주다: 2016-05-16 18:09:35
원래의
1488명이 탐색했습니다.

이미지가 레이아웃을 깨뜨리는 것을 방지하기 위해 가장 일반적인 방법은 로딩 후 이미지 크기를 얻은 다음 이를 조정하여 로딩 프로세스 중에 여전히 깨지도록 하는 것입니다. 여기에서 Qzone 로그의 그림이 개선되었으며, 온로드가 완료된 후 원본 그림이 표시됩니다. 이전에 onload를 사용하여 간단한 예제를 작성한 적이 있습니다. http://www.planeart.cn/?p=1022
imgReady를 사용하면 img가 로드될 때까지 기다리지 않고 DOM Ready에서 크로스 브라우저 이미지 적응을 달성할 수 있습니다.

코드 복사 코드는 다음과 같습니다

// jQuery.autoIMG.js v0.2
// Tang Bin - http://planeArt.cn/ - MIT 라이센스
(function ($) {
var // 로딩 상태에 대한 대체 이미지 설정
tempPath = './images/loading.png',
// 로딩 오류에 대한 대체 이미지 설정
errorPath = './images/error.png',
// css2.1 max-width 속성이 지원되는지 확인
isMaxWidth = 'maxWidth' in document.documentElement.style,
// IE7 브라우저가 지원되는지 확인
isIE7 = !- [1,] && !(이미지의 '프로토타입') && isMaxWidth;
new Image().src = tempPath
$.fn.autoIMG = function () {
var $this,
// 컨테이너 너비 가져오기
maxWidth = $this.width();
return $this.find('img').each(function (i, img) {
// 다음 경우에 사용 max-width 속성이 지원됩니다. 그렇지 않으면 다음 사전 로드 방법을 사용하십시오.
if (isMaxWidth) return img.style.maxWidth = maxWidth 'px'
var path = img.getAttribute('data-src') || img.src,
next = img.nextSibling,
parent = img.parentNode,
temp = new Image()
// img 이미지를 삭제하고 로딩 이미지로 교체합니다
img.style.display = 'none';
img.parentNode.removeChild(img);
tempPath
다음 .insertBefore(temp) : parent .appendChild(temp);
// 이미지 크기 실행 준비
imgReady(path, function (width, height) {
if (width > maxWidth) {
// 비례적으로 크기 조정
height = maxWidth / width * height,
width = maxWidth;
//로딩 이미지 삭제
temp.parentNode.removeChild(temp); 조정된 원본 이미지를 복원합니다
img.style.display = '';
img.style.width = 너비 'px';
img.style.height = 높이 'px'; setAttribute('src', path );
next ? next.insertBefore(img) : parent.appendChild(img);
}
}, function () {
// 로딩 오류 🎜>temp.src = errorPath ;
temp.title = '이미지 로드 오류!';
})
}// IE7 확대/축소 이미지가 왜곡됩니다. , 개인 속성을 사용하여 3차 보간
isIE7 && (function (c,d,s) {s=d.createElement('style');d.getElementsByTagName('head')[0].appendChild( s);s.styleSheet&&(s.styleSheet .cssText =c)||s.appendChild(d.createTextNode(c))})('img {-ms-interpolation-mode:bicubic}',document)
// 이미지 헤더의 크기 데이터 가져오기
// http://www.planeart.cn/?p=1121
// @param {String} 이미지 경로
// @param { Function} 크기를 가져오는 콜백 함수(매개변수 1은 너비를 수신하고 매개변수 2는 높이를 수신함)
// @param {Function} 로딩 오류 콜백 함수(선택 사항)
var imgReady = 함수(url, 콜백, 오류) {
var width, height, offsetWidth, offsetHeight, IntervalId, check, div,
accuracy = 1024,
doc = document,
container = doc.getElementsByTagName('head' )[0],
img = new Image();
img.src = url
// 이미지가 캐시된 경우 캐시된 데이터를 직접 반환합니다.
if (img.complete) {
return callback(img.width, img.height)
};
// 페이지에 비밀 이미지를 삽입하고 이미지 크기 준비 상태를 모니터링합니다.
if (container) {
div = doc.createElement('div');
div .style.cssText = 'visibility:hidden;position:absolute;left:0;top:0;width:1px;height:1px;overflow:hidden';
div.appendChild(img)
container.appendChild(div);
width = img.offsetWidth;
height = img.offsetHeight;
check = function () {
offsetWidth = img.offsetWidth;
offsetHeight = img.offsetHeight;
// 이미지 크기가 변하기 시작하면 브라우저가 이미지 헤더 데이터를 획득하여 점유했다는 뜻입니다
// 실제 테스트 후, img.offsetWidth 모니터링만 유효하고 img.offsetHeight 감지는 보험용입니다
/ / 새로 삽입되는 이미지의 면적이 미리 설정된 크기보다 크다면 실행 전 이미지가 다른 곳에서 로딩되고 있을 가능성이 높습니다 , 예를 들어 웹킷 기반 브라우저
if (offsetWidth !== width || offsetHeight !== height || offsetWidth * offsetHeight > Accuracy) {
clearInterval(intervalId)
callback(offsetWidth, offsetHeight);// IE 메모리 누수를 방지하기 위해 img 이벤트 및 요소 삭제
img.onload = null ;
div.innerHTML = ''
div.parentNode.removeChild(div); 🎜>};
};
check();
// 정기적으로 감지 수행
intervalId(check, 150)
}// 이미지를 기다립니다. 완전히 로드됨
// 이는 보험 작업이므로 위의 크기 모니터링 방법이 실패하면 활성화됩니다
// 아주 작은 이미지의 로드 시간이 감지 간격보다 짧을 가능성이 있는 경우 타이머에 의해 정의되면 타이머가 중지됩니다.
img.onload = function () {
callback(img.width, img.height)
img.onload = img.onerror = null; >clearInterval(intervalId);
container && img.parentNode.removeChild(img);
};
// 이미지 로딩 오류
img.onerror = function () {
error && error ();
clearInterval(intervalId);
container && img.parentNode.removeChild(img)
})(jQuery);
autoIMG 압축: 1.74kb, 호환 가능: Chrome | IE7 | IE8 |
데모 호출: $('#demo p').autoIMG()
, 유쾌한 DEMO 주소는 여기 있습니다: http://demo.jb51.net/js/2011/autoimg/
추첨: 이전 글에서 imgReady 기술에 대한 예감이 있었지만, 이 이미지 적응형 플러그인을 구현하는 것은 매우 간단하겠지만, 그 과정에서 웹킷 기반의 브라우저에 문제가 발생했고, 나중에 웹킷에 수정되지 않은 버그가 있다는 것을 알게 되었습니다. imgReady 기능을 업데이트했습니다.
패키지 다운로드 주소
관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!